2013-08-23 2 views
2

Activity라는 클래스에 바인딩 된 데이터 뷰가 있습니다. 그리드에는 체크 박스 열과 텍스트 상자 인 두 개의 열이 있습니다.WPF에서 데이터 뷰 값을 기반으로 버튼을 사용하도록 설정 한 경우

확인란 중 하나 이상을 선택하고 텍스트 상자 중 하나에 특정 문자열이있는 경우 단추를 활성화하는 코드를 추가하고 싶습니다. 나는 Activity 클래스에서 새로운 Property를 생성하고 그것을 "isEnabled"속성에 바인딩하는 것에 대해 생각했지만 NotifyPropertyChanged를 발생시키는 set 메소드가 없으므로 작동하지 않을 것이라고 확신하지 못했습니다.

제안 사항? 당신이 이렇게 사용하는 NotifyPropertyChanged 이벤트를 필요로하지 않는 자체 평가되는 CanExecute 기능을 가지고 있기 때문에 행동의이 종류를 수행 할 RelayCommand을 활용할 수 위의 내 의견으로 당

<DataGrid Name="dataGrid" HorizontalAlignment="Center" CanUserAddRows="False" CanUserReorderColumns="False" HeadersVisibility="Column" Margin="0,28,0,0" VerticalAlignment="Top" Height="262" AutoGenerateColumns="False" ItemsSource="{Binding Activities}" SelectedItem="{Binding SelectedActivity, Mode=TwoWay}"> 
     <DataGrid.Columns> 
      <DataGridTemplateColumn Header="Enabled"> 
       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <CheckBox HorizontalAlignment="Center" VerticalAlignment="Center" IsChecked="{Binding Enabled, UpdateSourceTrigger=PropertyChanged}"/> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
      </DataGridTemplateColumn> 
+0

(모든 ITE "Item6"모든 항목이 선택하고있다) 필요한 경우 CanExecute 메서드에 대한 논리는이 경우 트릭을 수행해야합니다. –

+0

Relay 명령을 사용하여 CanExecute에서 선택한 속성 값을 확인할 수 있습니다. –

답변

2

/를 Button

을 해제 다음은 전체 예제는 하드 조금 설명

XAML이 될 수있는이 작업을 보여주고있다 :

<Window x:Class="WpfApplication8.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="315" Width="258" Name="UI"> 

    <Grid DataContext="{Binding ElementName=UI}"> 
     <DataGrid Name="dataGrid" CanUserAddRows="False" CanUserReorderColumns="False" HeadersVisibility="Column" AutoGenerateColumns="False" ItemsSource="{Binding Activities}" SelectedItem="{Binding SelectedActivity, Mode=TwoWay}" Margin="10,10,10,37" > 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Column1" Binding="{Binding Column1}" /> 
       <DataGridTemplateColumn Header="Enabled"> 
        <DataGridTemplateColumn.CellTemplate> 
         <DataTemplate> 
          <CheckBox HorizontalAlignment="Center" VerticalAlignment="Center" IsChecked="{Binding Enabled, UpdateSourceTrigger=PropertyChanged}"/> 
         </DataTemplate> 
        </DataGridTemplateColumn.CellTemplate> 
       </DataGridTemplateColumn> 
      </DataGrid.Columns> 
     </DataGrid> 
     <Button Command="{Binding MyButtonCommand}" Content="Is any checked &amp; is any 'Item6' " Margin="10,0,9,10" Height="22" VerticalAlignment="Bottom"/> 
    </Grid> 
</Window> 

코드 :

namespace WpfApplication8 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     private ObservableCollection<TestObject> myVar = new ObservableCollection<TestObject>(); 

     public MainWindow() 
     { 
      MyButtonCommand = new RelayCommand(ExecuteButtonAction, CanButtonExecute); 
      InitializeComponent(); 

      for (int i = 0; i < 100; i++) 
      { 
       Activities.Add(new TestObject { Column1 = "Item" + i, Enabled = false }); 
      } 
     } 

     public ICommand MyButtonCommand { get; set; } 

     public ObservableCollection<TestObject> Activities 
     { 
      get { return myVar; } 
      set { myVar = value; } 
     } 

     private bool CanButtonExecute() 
     { 
      return Activities.Any(x => x.Enabled) && Activities.Any(x => x.Column1 == "Item2"); 
     } 

     private void ExecuteButtonAction() 
     { 
      // button clicked 
     } 
    } 


    public class TestObject : INotifyPropertyChanged 
    { 

     private string _column1; 
     private bool _enabled; 

     public string Column1 
     { 
      get { return _column1; } 
      set { _column1 = value; NotifyPropertyChanged(); } 
     } 

     public bool Enabled 
     { 
      get { return _enabled; } 
      set { _enabled = value; NotifyPropertyChanged(); } 
     } 


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

    public class RelayCommand : ICommand 
    { 
     private readonly Action _execute; 
     private readonly Func<bool> _canExecute; 

     /// <summary> 
     /// Creates a new command that can always execute. 
     /// </summary> 
     /// <param name="execute">The execution logic.</param> 
     public RelayCommand(Action execute) 
      : this(execute, null) 
     { 
     } 

     /// <summary> 
     /// Creates a new command. 
     /// </summary> 
     /// <param name="execute">The execution logic.</param> 
     /// <param name="canExecute">The execution status logic.</param> 
     public RelayCommand(Action execute, Func<bool> canExecute) 
     { 
      if (execute == null) 
       throw new ArgumentNullException("execute"); 

      _execute = execute; 
      _canExecute = canExecute; 
     } 

     [DebuggerStepThrough] 
     public bool CanExecute(object parameter) 
     { 
      return _canExecute == null ? true : _canExecute(); 
     } 

     public event EventHandler CanExecuteChanged 
     { 
      add 
      { 
       if (_canExecute != null) 
       { 
        CommandManager.RequerySuggested += value; 
       } 
      } 
      remove 
      { 
       if (_canExecute != null) 
       { 
        CommandManager.RequerySuggested -= value; 
       } 
      } 
     } 

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

} 

결과 : 버튼에 RelayCommand 또는 DelegateCommand를 사용하고 추가

enter image description hereenter image description here

관련 문제