c# - 如何在ListView WPF中将命令绑定(bind)到复选框?

标签 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;
    }        
}
}

据我所知,这似乎应该有效,但是当我选中/取消选中该复选框时,消息框未激活。为了使检查/取消检查命令正常工作,我缺少什么?

最佳答案

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

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

关于c# - 如何在ListView WPF中将命令绑定(bind)到复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43416802/

相关文章:

android - 如何通过dataBinding访问fragment中activity的父 View

c# - 如何将适度大量的数据传递到我的 Web API 应用程序?

c# - 如何在 C# 中实现线程安全的无错误事件处理程序?

wpf - 更改位置标记/插入符的颜色

javascript - 这个 Angular 代码有什么问题?

c# - 在 WinForms 中更新 BindingSource 不会更新数据源集合

c# - <% : %> and <%#: %> in Asp.Net 之间的差异

c# - 为 SVN 修改提交时的文本文件,让我的程序知道它的提交号

c# - 有没有一种简单的方法可以将命令绑定(bind)到 MVVM WPF 中的列表框?

c# - 如何关闭在 WPF 中用作子菜单的弹出窗口