【问题标题】:How to bind IsSelected property of DataGrid row to a source property如何将 DataGrid 行的 IsSelected 属性绑定到源属性
【发布时间】:2022-07-09 03:57:25
【问题描述】:

我有一个 DataGrid 并将其项目源绑定到下面的类列表。如何将数据网格行 IsSelected 属性绑定到类 IsChecked 属性?

public class DeckInt : INotifyPropertyChanged
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool isChecked { get; set; }


        public int Id { get { return id; } set { id = value; OnPropertyChanged(nameof(Id)); } }
        /// <summary>
        /// Group name of the weight item
        /// </summary>
        public string Name { get { return name; } set { name = value; OnPropertyChanged(nameof(Name)); } }
        public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged(nameof(IsChecked)); } }

        public event PropertyChangedEventHandler PropertyChanged;

        //When propert changes, notify
        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

【问题讨论】:

标签: c# wpf data-binding binding datagrid


【解决方案1】:

您需要一个绑定代理类来绑定到数据网格。

public class BindingProxy : Freezable
{
    public static readonly DependencyProperty DataProperty =
       DependencyProperty.Register("Data", typeof(object),
          typeof(BindingProxy), new UIPropertyMetadata(null));

    public object Data
    {
        get { return GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion
}

之后你需要重新引用它,无论它在 xaml 中有什么命名空间。

xmlns:proxy="clr-namespace:Infinity.bindingproxy"

并将您需要的任何属性/命令绑定到数据网格资源

<DataGrid.Resources>
    <proxy:BindingProxy x:Key="IsChecked " Data="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid.Resources>

并将其绑定到 Datagrid 中的复选框

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding Data, Source={StaticResource ViewIfActive}, UpdateSourceTrigger=PropertyChanged"/>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2020-08-05
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多