根据MVVM中的复选框列表选择启用WPF按钮

时间:2016-07-28 10:20:49

标签: c# wpf xaml mvvm

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

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()。

1 个答案:

答案 0 :(得分: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

相关问题