在我们wpf开发中,很多人会有mvvm模式去做wpf的项目。

是否有人遇到这样一个场景:在一个界面上,有个tabcontrol上面有4个页签,每个页签里面都有一个datagrid,里面显示的列基本一样,绑定的数据集合都是同一个,但是有个差异,在第二个页签上需要第二列不显示,第三个页签只显示一个列。

我们如果用的是mvvm,这个时候就会去使用数据绑定,问题在于我们怎么让datagrid的下一级也就是DataGridTextColumn识别到vm,或者怎么在模板列中识别vm,可以绑定我们在vm中声明的显示隐藏属性。

这里有个方案:

public class BindingProxy : Freezable
    {
        protected override Freezable CreateInstanceCore()
        {
            throw new NotImplementedException();
        }

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

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    }

很简单的方式,定义一个空对象用来转接vm,将vm存入Data。

下面是用法:

WPF实战案例-数据代理

很简单的方式。但是这个的使用场景还是比较多的,在很多绑定操作的时候,因为层级的关系有时候不一定能找到需要的对象,通过这个代理做一个转接的作用。

 有对WPF感兴趣的同学,可以加页面下方的qq群,我们一起共同进步!

相关文章:

  • 2022-01-15
  • 2021-07-26
  • 2021-05-30
  • 2022-12-23
  • 2023-01-09
  • 2021-11-20
  • 2021-07-30
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2021-10-04
  • 2021-12-04
  • 2021-08-14
  • 2023-03-05
相关资源
相似解决方案