2017-11-23 8 views
0

내가 WPF와 MVVM에 새로운 오전 나는 다음과 같은 질문

동일한 명령으로 상대 바인딩을 만들 수 있습니까?

  1. 나는 하나 개의 버튼을 클릭하면 내가 3 개 버튼
  2. 이를 가지고, 그것은 예를 들어, CommandParameter을 가져옵니다 0,1
  3. 명령 SetBackGround
  4. 지금 나는 setti에 대한 조건을 가지고 IsSelectedBackground 바인딩하려고 추출 행과 열에 대한 CommandParameter 분할 나는 모든 버튼을 클릭하면 ... Background
  5. 문제입니다 겨 .. 그들은 노란색 Background을 설정,하지만 난 단지 이 올바른 상태이 버튼을 필요로하므로

마 각 버튼마다 다른 배경을 만들어야합니까? 아니면 다른 방법이 있습니까?

누가이 말을 ... "조건"매개 변수가 그 배경을 노란색으로 설정하고 다른 것들은 그렇지 않은지.

이미지

image

뷰 모델

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Linq; 
using System.Text; 
using System.Windows.Input; 
using Testing00.Commands; 

namespace Testing00.ViewModels 
{ 
    public class ViewModel : INotifyPropertyChanged 
    { 

     public ICommand SetBackGroundCommand { get; set; } 
     bool LeftSelected { get; set; } 
     bool RightSelected { get; set; } 

     #region Methods 
     int row; 
     public int Row 
     { 
      get { return row; } 
      set { row = value; } 
     } 

     int column; 
     public int Column 
     { 
      get { return column; } 
      set { column = value; } 
     } 

     public bool IsSelected 
     { 
      get 
      { 
       if (row == 0 && column == 0) 
       { 
        return false; 
       } 
       else 
       { 

        return true; 
       } 
      } 
      set 
      { 
       OnPropertyChanged("IsSelected"); 
       OnPropertyChanged("Background"); 
      } 
     } 

     public string Background 
     { 
      get 
      { 
       return IsSelected ? "Yellow" : "Transparent"; 
      } 
     } 

     #endregion 


     #region Constructor 

     public ViewModel() 
     { 
      SetBackGroundCommand = new RelayCommand(SetBackGround, param => true); 
     } 

     #endregion 

     private void SetBackGround(object obj) 
     { 
      string[] commandParametters = obj.ToString().Split(','); 
      Row = Convert.ToInt32(commandParametters[0]); 
      Column = Convert.ToInt32(commandParametters[1]); 
      OnPropertyChanged("IsSelected"); 
      OnPropertyChanged("BackGround"); 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
     public void OnPropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 

    } 
} 

MainWindows

<Window x:Class="Testing00.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:TEST="clr-namespace:Testing00.ViewModels" 
     xmlns:local="clr-namespace:Testing00" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <TEST:ViewModel x:Key="testVM"></TEST:ViewModel> 
    </Window.Resources> 
    <Grid> 
     <Button Content="0,0" HorizontalAlignment="Left" Margin="84,109,0,0" VerticalAlignment="Top" Width="79" Height="81" CommandParameter="0,0" Command="{Binding SetBackGroundCommand, Source={StaticResource testVM}}" Background="{Binding Background, Mode=OneWay, Source={StaticResource testVM}}" /> 
     <Button Content="0,1" HorizontalAlignment="Left" Margin="208,109,0,0" VerticalAlignment="Top" Width="79" Height="81" CommandParameter="0,1" Command="{Binding SetBackGroundCommand, Source={StaticResource testVM}}" Background="{Binding Background, Mode=OneWay, Source={StaticResource testVM}}" /> 
     <Button Content="0,2" HorizontalAlignment="Left" Margin="341,109,0,0" VerticalAlignment="Top" Width="79" Height="81" CommandParameter="0,2" Command="{Binding SetBackGroundCommand, Source={StaticResource testVM}}" Background="{Binding Background, Mode=OneWay, Source={StaticResource testVM}}" /> 
    </Grid> 
</Window> 
012 3,516,

RelayCommand

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Input; 

namespace Testing00.Commands 
{ 
    public class RelayCommand : ICommand 
    { 

     Action<object> _execute; 
     Func<object, bool> _canexecute; 
     public RelayCommand(Action<object> execute, Func<object, bool> canexecute) 
     { 
      _execute = execute; 
      _canexecute = canexecute; 

     } 
     public bool CanExecute(object parameter) 
     { 
      if (_canexecute != null) 
      { 
       return _canexecute(parameter); 
      } 
      else 
      { 
       return false; 
      } 
     } 

     public event EventHandler CanExecuteChanged 
     { 
      add { CommandManager.RequerySuggested += value; } 
      remove { CommandManager.RequerySuggested -= value; } 
     } 

     public void Execute(object parameter) 
     { 
      _execute(parameter); 
     } 
    } 
} 
+0

이것은 XY 문제와 비슷합니다 ... 버튼으로 무엇을하고 싶은지, 왜 뷰 모델이 선택된 버튼 (그리고 선택된 버튼이 실제로 무엇인지)에 대해 왜 더 설명해야하는지 알 수 있습니다. 선택할 수있는 버튼이 필요하다면,'ToggleButton'을 만들고'IsChecked' 속성에 따라 배경을 변경할 것입니다. viewmodel은 배경을 신경 쓰지 않고,'IsSelected' 부울 또는 그와 비슷한 것을 사용할 것입니다. – grek40

+0

내 경우에는 조건에 따라 버튼 그룹을 선택해야합니다. 예를 들어 미래에 두 개의 버튼을 "왼쪽 또는 오른쪽"으로 추가하면 ** 왼쪽 **을 선택한 다음 내용이 0,1 인 버튼을 선택해야합니다. ,이 예제에서 0,1 & 0,0은 BackGround를 노란색으로 설정하고 오른쪽을 0,2로 설정해야합니다. ViewModel의 해당 버튼에 대한 배경은 조건에 따라 다릅니다. 감사합니다 –

+1

글쎄요 ... 바인딩이 개별적으로 작동하려면 각 버튼에 개별 속성이 필요합니다. – grek40

답변

0

대략, 거의 코드가 (당신이 ItemsControl 찾는 경우가 더 찾을 수 있습니다) 입증되면서 grek40 말했듯이 당신이 할 수 있습니다.

버튼은 고유 한 viewmodel과 속성을 가진 usercontrol (ucMyButton)이됩니다. 당신의 MAINVIEW에서

당신은 ItemControl 추가 할 것입니다 그리고 그것은 한 버튼의 컬렉션 (ObservableCollection<MyButtonViewModel> MyButtons { ..... })

각 MyButtonViewModel는 각각의 버튼을 별도로

설정할 수 있습니다 자신의 배경 속성을 별도의 버튼이 될 것입니다 포함됩니다
<ItemsControl x:Name="itmWrapPanel" 
      ItemsSource="{Binding MyButtons, UpdateSourceTrigger=PropertyChanged}" 

      ScrollViewer.CanContentScroll="True" 
      ScrollViewer.VerticalScrollBarVisibility="Auto" 
      ScrollViewer.HorizontalScrollBarVisibility="Auto" 
      > 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel Orientation="Horizontal" 
        Background="White" 
        AllowDrop="True" 
        Width="{Binding ActualWidth, ElementName=itmWrapPanel}" 
        Height="{Binding ActualHeight, ElementName=itmWrapPanel}" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <ItemsControl.ItemTemplate> 
     <DataTemplate > 
      <local:ucMyButton /> 

     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl>