【问题标题】:Other checkboxes in different rows are checked when a checkbox is checked选中复选框时会选中不同行中的其他复选框
【发布时间】:2019-03-31 20:21:24
【问题描述】:

我有一个网格,每行(其中 300 行)由“string | string | int | string | check”组成。例如,如果我单击第 7 行中的复选框,则不会发生任何异常情况。但是,如果我单击另一行上的另一个复选框,我可能会得到 10 个其他行的复选框已选中,但这些其他复选框不会执行与它们关联的代码。

            <DataGridTemplateColumn Width="*" Header="Add">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>                           
                        <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

【问题讨论】:

    标签: wpf checkbox datagrid


    【解决方案1】:

    这是因为行视觉效果被重复使用。您可以设置&lt;DataGrid EnableRowVirtualization="False"...,但如果有很多行,这将对性能产生巨大影响。更好的解决方案是使用 ViewModel 来存储检查状态。然后将值绑定到 ViewModel &lt;CheckBox IsChecked="{Binding MyBoolProperty}"...

    在您的 ViewModel 中,您可以在属性更改时调用您的方法。

    public class MyItem
    {
        //.... other class info
        //TODO: Implement INotifyPropertyChanged
    
        private bool _MyBoolProperty = false;
        public bool MyBoolProperty
        {
            get
            {
                return _MyBoolProperty;
            }
            set
            {
                _MyBoolProperty = value;
                MyBoolPropertyChanged();
            }
        }
    
        private void MyBoolPropertyChanged()
        {
            //do something
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 2013-06-24
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多