WPF之使用“依赖属性”实现动态添加DataGrid“头”和“列”(MVVM模式)

1、首先自定义控件——DataGridEx

添加依赖属性:DynamicBindHeadersCols

    /// <summary>
    /// DataGridEx.xaml 的交互逻辑
    /// </summary>
    public partial class DataGridEx : DataGrid
    {
        /// <summary>
        /// 动态绑定DataGrid头和列
        /// </summary>
        public DataGrid DynamicBindHeadersCols
        {
            get { return (DataGrid)GetValue(DynamicBindHeadersColsProperty); }
            set { SetValue(DynamicBindHeadersColsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for dataGrid.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DynamicBindHeadersColsProperty =
            DependencyProperty.Register("DynamicBindHeadersCols", typeof(DataGrid), typeof(DataGridEx), new PropertyMetadata((s, e) =>
            {
                var dp = s as DataGridEx;
                foreach (var item in (e.NewValue as DataGrid).Columns)
                {
                    dp.Columns.Add(new DataGridTextColumn()
                    {
                        Header = item.Header,
                        Binding = item.ClipboardContentBinding,
                        Width = item.Width,
                        Visibility = item.Visibility,
                        IsReadOnly = item.IsReadOnly,
                    });
                }
            }));
    }

2、前台Xaml代码:

    <Grid>
        <controlex:DataGridEx ItemsSource="{Binding TestValues}" Style="{StaticResource DataGridExStyle}" DynamicBindHeadersCols="{Binding DataGrids}" />
    </Grid>

3、ViewModel代码:

    public class MainViewModel : INotify
    {
        public object TestValues { get; set; }
        public MainViewModel()
        {
            DataGridLength length = new DataGridLength(1, DataGridLengthUnitType.Star);
            dataGrids.Columns.Add(new DataGridTextColumn() { Header = "姓名", Binding = new Binding("Name"), Width = length, IsReadOnly = true });
            dataGrids.Columns.Add(new DataGridTextColumn() { Header = "年龄", Binding = new Binding("Age"), Width = length, IsReadOnly = false });
            TestValues = new[] {
                new { Name = "张三", Age = 23 },
                new { Name = "李四", Age = 24 },
                new { Name = "王五", Age = 25 },
            };
        }

        private DataGrid dataGrids = new DataGrid();

        public DataGrid DataGrids
        {
            get { return dataGrids; }
            set
            {
                dataGrids = value;
                RaisePropertyChanged();
            }
        }
    }

4、实现效果:

 

 不到之处请大家多多指正,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值