绑定复选框命令

本文关键字:命令 复选框 绑定 | 更新日期: 2023-09-27 18:23:53

列表视图中的每一行都有一个复选框。我想将复选框OnClick绑定到视图模型中的命令。但它对我的命令没有约束力。我该怎么办?下面是我的xaml和Viewmodel

Xaml:

<Grid>
        <ListView Name="lstdemo" ItemsSource="{Binding obcollection}">
            <ListView.View>
                <GridView>
                    <GridView.Columns>
                        <GridViewColumn>
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <CheckBox Name="chk" IsChecked="{Binding IsChecked,Mode=TwoWay,NotifyOnTargetUpdated=True}" Command="{Binding Path=UpdateCommand}" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" />
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

ViewModel:

public class MyViewModel
    {
        private List<Demo> lstdemo;
        private ObservableCollection<Demo> Obcollection;
        private SampleDb db;
        public MyViewModel()
        {
            db = new SampleDb();
            lstdemo = db.Demoes.ToList();
            Convert();
        }
        public void Convert()
        {
            Obcollection = new ObservableCollection<Demo>(lstdemo);
        }
        public ObservableCollection<Demo> obcollection
        {
            get { return Obcollection; }
            set { Obcollection = value; }
        }
        private ICommand mUpdater;
        public ICommand UpdateCommand
        {
            get
            {
                if (mUpdater == null)
                    mUpdater = new Updater();
                return mUpdater;
            }
            set
            {
                mUpdater = value;
            }
        }
        public class Updater : ICommand
        {
            #region ICommand Members
            public bool CanExecute(object parameter)
            {
                return true;
            }
            public event EventHandler CanExecuteChanged;
            public void Execute(object parameter)
            {
                if (parameter == null)
                {
                    MessageBox.Show("Hello");
                }
            }
            #endregion
        }
    }

绑定复选框命令

DataTemplate中的DataContext隐含地是(ListView的)当前项。因此,在这种情况下,您必须显式设置Binding的Source(或RelativeSource)。您可以使用RelativeSource来查找父ListView,如下所示:

<CheckBox Name="chk" IsChecked="{Binding IsChecked,
                                 Mode=TwoWay,NotifyOnTargetUpdated=True}" 
          Command="{Binding Path=DataContext.UpdateCommand, 
                    RelativeSource={RelativeSource AncestorType=ListView}}"/>

关于Path更改的注意事项。源现在是ListView,所以到UpdateCommand的路径是DataContext.UpdateCommand