【问题标题】:WPF Datagrid checkbox column checked选中 WPF Datagrid 复选框列
【发布时间】:2018-06-24 07:30:35
【问题描述】:

我的数据网格复选框列:

                    <DataGridTemplateColumn MaxWidth="45">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="check_tutar"  VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Checked="check_tutar_Checked"></CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

我想访问此复选框并更改选中的属性。我尝试默认方法:check_tutar.IsChecked = false;

但没用,因为我无法使用名称访问复选框。如何更改数据网格列复选框选中的属性?

【问题讨论】:

    标签: c# wpf checkbox datagrid


    【解决方案1】:

    您应该将CheckBoxIsChecked 属性绑定到数据对象的bool 属性并设置此属性,而不是尝试访问CheckBox 控件本身:

    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox x:Name="check_tutar" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    

    数据类应实现INotifyPropertyChanged 接口并在设置IsChecked 属性以使其工作时发出更改通知:

    public class YourClass : INotifyPropertyChanged
    {
        private bool _isChecked;
        public bool IsChecked
        {
            get { return _isChecked; }
            set { _isChecked = value; NotifyPropertyChanged(); }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    然后您可以通过设置相应对象的IsChecked 属性来简单地选中/取消选中DataGrid 中一行的CheckBox,例如:

    List<YourClass> theItems = new List<YourClass>(0) { ... };
    dataGrid1.ItemsSource = theItems;
    
    //check the first row:
    theItems[0].IsChecked = true;
    

    这基本上就是 WPF 和 DataGrid 的工作原理。

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2011-07-18
      • 2013-06-11
      • 2013-11-01
      相关资源
      最近更新 更多