绑定CheckBox命令

时间:2014-09-22 17:55:15

标签: c# wpf xaml mvvm prism

列表视图中的每一行都有一个复选框。我想在视图模型中将Checkbox 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>

视图模型:

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
        }

    }

1 个答案:

答案 0 :(得分:0)

DataContext中的DataTemplate隐式地是(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