如何将命令绑定到ListView WPF中的复选框?

时间:2017-04-14 18:02:07

标签: c# wpf data-binding icommand relaycommand

更新

我编辑了以下代码以匹配建议,现在可以正常使用。

我已经看到了几个与此类似的堆栈溢出问题,但我还没有完全把它们放在一起。我有以下xaml代码。

<UserControl x:Class="AuditEfficiencyMVVM.View.AuditTestsMain"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:AuditEfficiencyMVVM.View"
         xmlns:viewmodel="clr-namespace:AuditEfficiencyMVVM.ViewModel"
         mc:Ignorable="d" 
         d:DesignHeight="500" d:DesignWidth="1000">

<UserControl.DataContext>
    <viewmodel:AuditTests/>
</UserControl.DataContext>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition/>
        <RowDefinition Height="50"/>
    </Grid.RowDefinitions>

    <ListView Grid.Row="1" Grid.Column="0" Margin="10" ItemsSource="{Binding Path=Tests}">
        <ListView.View>
            <GridView>
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Name="TestSelected" IsChecked="{Binding Path=Selected, Mode=TwoWay}" Command="{Binding Path=TestSelected, RelativeSource={RelativeSource AncestorType=ListView}}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Test Type" DisplayMemberBinding="{Binding Type, Mode=OneWay}"/>
                <GridViewColumn Header="Progress">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ProgressBar Name="TestProgress" Width="50" Height="20" Value="{Binding Progress, Mode=OneWay}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status, Mode=OneWay}"/>                    
            </GridView>
        </ListView.View>

        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate>
                                    <Expander IsExpanded="True">
                                        <Expander.Header>
                                            <TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Name}"/>
                                        </Expander.Header>
                                        <ItemsPresenter/>
                                    </Expander>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>

    <ListView Grid.Row="1" Grid.Column="1" Margin="10" ItemsSource="{Binding Path=Files}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="File Type" DisplayMemberBinding="{Binding Type, Mode=OneWay}"/>
                <GridViewColumn Header="File Location" Width="250">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Path=Location, Mode=TwoWay}" Width="225"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>                    
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Width="30" Height="20">...</Button>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

    <Button Grid.Row="2" Grid.Column="1" HorizontalAlignment="Right" Margin="10" Width="50" Height="30">Run</Button>
</Grid>
</UserControl>

这是我背后的代码

public class AuditTests : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private RelayCommand _testSelected;

    private void AddTest()
    {
        MessageBox.Show("Success");
    }

    public RelayCommand TestSelected
    {
        get
        {
            return _testSelected;
        }
        private set
        {
            if (_testSelected != value)
            {
                _testSelected = value;
                RaisePropertyChanged("TestSelected");
            }                
        }
    }

    private void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

    public AuditTests()
    {
        TestSelected = new RelayCommand(AddTest);
    }

    public ObservableCollection<Model.File> Files
    {
        get;
        set;
    }

    public ObservableCollection<Model.Test> Tests
    {
        get;
        set;
    }

    public void LoadFiles()
    {
        ObservableCollection<Model.File> files = new ObservableCollection<Model.File>();

        foreach (Model.Test test in Tests)
        {
            foreach (Enums.FileType type in test.ExpectedSources)
            {
                Boolean containsType = false;
                foreach (Model.File file in files)
                {
                    if (file.Type == type)
                    {
                        containsType = true;
                        break;
                    }
                }

                if (!containsType)
                {
                    files.Add(new Model.File { Type = type, Location = "", Tests = new List<Enums.TestType> { test.Type } });
                }
                else
                {
                    files.Where(t => t.Type == type).First().Tests.Add(test.Type);
                }
            }
        }

        Files = files;
    }

    public void LoadTests()
    {
        ObservableCollection<Model.Test> tests = new ObservableCollection<Model.Test>();

        foreach (var prop in Enum.GetValues(typeof(Enums.TestType)).Cast<Enums.TestType>().ToList())
        {
            tests.Add(new Model.Test { Category = prop.GetCategory(), Type = prop, Progress = 0, Selected = true, Status = Enums.TestStatus.NotStarted, ExpectedSources = prop.GetExpectedFiles() });
        }

        Tests = tests;
    }        
}
}

从我所看到的内容看起来似乎应该可行,但是当我选中/取消选中复选框时,消息框不会被激活。我在这里缺少什么来使check / uncheck命令工作?

2 个答案:

答案 0 :(得分:2)

TestSelected命令是属性AuditTests对象。 CheckBox的DataContext是Model.Test对象。它们处于不同的层面。您可以使用RelativeSource参数将命令绑定到ListView DataContext中的属性:

Command="{Binding Path=DataContext.TestSelected, 
                  RelativeSource={RelativeSource AncestorType=ListView}}"

答案 1 :(得分:1)

首先,我会AuditTests实施INotifyPropertyChanged,并在其值更改时在其所有属性设置器中引发PropertyChanged。这样做有很多文档。

其次,您必须为用户控制一份副本。我不知道你是否给了你的UserControl自己的MainWindow可能想要绑定的任何属性;如果是这样的话,这是一个更复杂的问题。但最简单的是:

public AuditTestsMain()
{
    InitializeComponent();

    //  Now its parent view can't bind this guy's properties to properties of the 
    //  parent's view's viewmodel, because we've broken DataContext inheritance. 
    DataContext = new ViewModels.AuditTests();
}

然后看看ASh关于如何绑定命令的答案。那是另一个DataContext的事情:那里的listview项是Model.Test个实例。因此,在项目的DataTemplate内,绑定默认绑定到Model.Test的属性,因为那是DataContext。但该命令不是Model.Test的属性;它是AuditTests的属性。 AuditTests是UserControl的DataContext,因此它也是ListView的DataContext。控件继承父的DataContext,除非有什么东西干扰它 - 比如我添加到你的AuditTestsMain构造函数的行,或者像ListView创建子列表的方式,它们将listview的项作为它们的DataContext。