复选框未在ListView中显示为已选中

时间:2015-05-19 22:04:11

标签: wpf mvvm

我在listview中有一个复选框。列表视图绑定到可观察的集合。当我使用上下文菜单尝试选择所有复选框时,它们不会显示为已选中。我做错了什么?

<ListView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding AvailableModels}"
           HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
           SelectionMode="Extended">
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Select All Models" Command="{Binding 
                      SelectAllModelsAction}" />
            <MenuItem Header="Deselect All Models" Command="{Binding 
                      DeselectAllModelsAction}" />
        </ContextMenu>
    </ListView.ContextMenu>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{Binding DataContext.IsSelected, 
                          RelativeSource={RelativeSource 
                          FindAncestor, AncestorType={x:Type 
                          ListViewItem}}}" VerticalAlignment="Center" />
                <Label Content="{Binding Name}" Margin="2,0,0,0" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

视图模型

public ObservableCollection<ListItems> AvailableModels
{
    get
    {
        return this.availableModels;
    }

    set
    {
        this.availableModels = value;

        this.NotifyPropertyChanged(m => m.AvailableModels);
    }
}

上下文菜单操作

private void SelectAllModels()
{
    foreach (var model in this.AvailableModels)
    {
        model.IsSelected = true;
    }

    this.NotifyPropertyChanged(m => m.AvailableModels);
}

ListItems对象

public class ListItems
{
    public string Name
    {
        get;

        set;
    }

    public object Value
    {
        get;

        set;
    }

    public bool IsSelected
    {
        get;

        set;
    }
}

1 个答案:

答案 0 :(得分:0)

ListItems未实施INotifyPropertyChanged,因此更改IsSelected并未更新用户界面。

SelectAllModels()中调用NotifyPropertyChanged是不必要的,因为集合本身不会更改。设置新集合时,NotifyProperyChanged() setter中的AvailableModels调用会更新UI。并且ObservableCollection将处理修改集合的时间(添加/删除项目)。但是,ListItems内的属性更改不会更新用户界面,除非他们在设置者中调用NotifyPropertyChanged