2016-07-28 81 views
1

我有一个复选框列表项和一个提交按钮。提交按钮最初需要被禁用。该按钮需要通过选择单个复选框选择或多个选择来启用。我在XAML中添加下面的代码,并且后端代码需要有一个视图模型起诉MVVM。启用基于MVVM中复选框列表选择的WPF按钮

XAML ..

<ListBox Grid.Row="1" BorderThickness="0" Background="Transparent" Name="list" ItemsSource="{Binding Items}" Margin="10 5 20 0" SelectionMode="Extended"> 
        <ListBox.ItemTemplate> 
         <DataTemplate> 
          <StackPanel Orientation="Horizontal"> 
           <CheckBox Name="check" IsChecked="{Binding IsChecked, Mode=TwoWay}" Margin="5 5 0 10" VerticalAlignment="Center" /> 
           <ContentPresenter Content="{Binding Value}" Margin="5 5 0 10"/> 
          </StackPanel> 
         </DataTemplate> 
        </ListBox.ItemTemplate> 
       </ListBox> 

<Button Grid.Row="2" Click="Button_Click" HorizontalAlignment="Right" Height="25" Width="60" Margin="0,0,30,0" IsEnabled="{Binding Path=IsButtonEnabled}">     <TextBlock>Submit</TextBlock> </Button> 

因此,如何将使用OnPropertyChanged视图模型实现()。

+0

也许有更好的方法来做到这一点,但为什么不使用绑定/多重绑定和转换器? –

+0

那么你可以添加一个使用转换器的答案吗? – indika

回答

0

您需要注册视图模型中每个项目的所有PropertyChanged事件并汇总结果。例如:

class ViewModel 
{ 
    public ViewModel() 
    { 
     Items = new ObservableCollection<Item>(); 

     PropertyChangedEventHandler propertyChangedHandler = (o, e) => 
     { 
      if (e.PropertyName == nameof(Item.IsChecked)) 
       OnPropertyChanged(nameof(IsButtonEnabled)); 
     }; 

     Items.CollectionChanged += (o, e) => 
     { 
      if (e.OldItems != null) 
       foreach (var item in e.OldItems.OfType<INotifyPropertyChanged>()) 
        item.PropertyChanged -= propertyChangedHandler; 
      if (e.NewItems != null) 
       foreach (var item in e.NewItems.OfType<INotifyPropertyChanged>()) 
        item.PropertyChanged += propertyChangedHandler; 
     }; 
    } 

    public ObservableCollection<Item> Items { get; } 

    public bool IsButtonEnabled => Items.Any(i => i.IsChecked); 
} 

另一个需要考虑的选项是使用ReactiveUI

+0

按钮的xaml应该是怎样的? – indika

+0

就像你写的一样。 –

+0

我也刚刚更新了代码,使用Any而不是All。 –