datagrid其中某列需要动态隐藏或显示的mvvm绑定方式,也可以用在其他表格类型控件上
版权归原作者所有。
[WPF] HOW TO BIND TO DATA WHEN THE DATACONTEXT IS NOT INHERITED
The DataContext
property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext
is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…
Let’s illustrate with a simple example: we want to display a list of products in a DataGrid
. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice
property exposed by the ViewModel. The obvious approach is to bind the Visibility
of the column to the ShowPrice
property:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding ShowPrice,
Converter={StaticResource visibilityConverter}}"/>
Unfortunately, changing the value of ShowPrice
has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)
The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement
to use to get the DataContext
, because the column doesn’t belong to the visual or logical tree of the DataGrid
.
We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid
itself:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding DataContext.ShowPrice,
Converter={StaticResource visibilityConverter},
RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>
Or we can add a CheckBox
bound to ShowPrice
, and try to bind the column visibility to the IsChecked
property by specifying the element name:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding IsChecked,
Converter={StaticResource visibilityConverter},
ElementName=chkShowPrice}"/>
But none of these workarounds seems to work, we always get the same result…
At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider
The solution to our problem is actually quite simple, and takes advantage of the Freezable
class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable
objects can inherit the DataContext
even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…
The idea is to create a class (I called it BindingProxy
for reasons that should become obvious very soon) that inherits Freezable
and declares a Data
dependency property:
public class BindingProxy : Freezable
{
#region Overrides of Freezable protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
} #endregion 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));
}
We can then declare an instance of this class in the resources of the DataGrid
, and bind the Data
property to the current DataContext
:
<DataGrid.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>
The last step is to specify this BindingProxy
object (easily accessible with StaticResource
) as the Source
for the binding:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding Data.ShowPrice,
Converter={StaticResource visibilityConverter},
Source={StaticResource proxy}}"/>
Note that the binding path has been prefixed with “Data”, since the path is now relative to the BindingProxy
object.
The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice
property.
datagrid其中某列需要动态隐藏或显示的mvvm绑定方式,也可以用在其他表格类型控件上的更多相关文章
- C#控件——批量化隐藏或显示同类型控件
当一个页面中添加了许多同类型控件,当需要控制这些控件进行显示或隐藏的时候,需要一个个的将Visible属性设置为false,十分不方便, 后通过论坛受一位大神(至于叫什么忘了)的启发,通过建立控件数组 ...
- 表格树控件QtTreePropertyBrowser编译成动态库(设计师插件)
目录 一.回顾 二.动态库编译 1.命令行编译动态库和测试程序 2.vs工具编译动态库和测试程序 3.安装文档 4.测试文档 三.设计师插件编译 1.重写QDesignerCustomWidgetIn ...
- iOS UITableView动态隐藏或显示Item
通过改变要隐藏的item的高度实现隐藏和显示item 1.创建UITableView #import "ViewController.h" @interface ViewContr ...
- 动态创建的文本框想要加上jQuery的datepicker功能变成日期选择控件该怎么办?
通常页面输入控件想得到日期选择功能,借助jQuery是这样实现的: 1.载入css和js <script src="jqueryui/jquery-ui.js" type=& ...
- JQuery动态隐藏和显示DIV
<head> <script language="javascript"> function HideWeekMonth() { $("#tt1& ...
- react中如何实现一个按钮的动态隐藏和显示(有效和失效)
初始准备工作 constructor(props) { super(props); /* * 构建导出数据的初始参数,结合用户下拉选择后动态设置参数值 * */ this.state = { btnS ...
- 关于使用MVVM模式在WPF的DataGrid控件中实现ComboBox编辑列
最近在做一个组态软件的项目,有一个需求需要在建立IO设备变量的时候选择变量的类型等. 建立IO变量的界面是一个DataGrid实现的,可以一行一行的新建变量,如下如所示: 这里需要使用带有ComboB ...
- DevExpres表格控件运行时动态设置表格列
本文是系列文章,陆续发表于电脑编程技巧与维护杂志. DevExpres产品是全球享有极高声誉的一流控件套包产品!国内典型用户包括:用友.金蝶.神州数码.工信部.中国石化.汉王科技等众多大中型科技型企业 ...
- GridView绑定数据与隐藏指定控件(模板列)
1.1. GridView绑定数据 1) 可以配置SqlDataSource数据源,修改select语句生成框架(不想手动绑定) 2) 删除DataSourceID属性和 ...
随机推荐
- CPU子系统
CPU的基本结构: CPU的主要部件: 运算部件.缓存部件.寄存器.控制器.时序部件 CPU的工作原理: 主要功能:处理指令.执行操作.控制时间.数据运算 执行指令的流程:读取指令.指令译 ...
- vue和react之间的区别
1.Vue和React之间的区别 相同点: Vue和其他框架一样,都有组件开发和虚拟dom 都支持props进行父子组件之间的数据通信 都支持数据驱动视图,不直接操作真实dom 都支持服务器端的 渲染 ...
- Flask 实现登陆 + session
Flask 实现登陆 + session 案例一: # -*- coding: utf-8 -*- # @Time : 2019/9/24 16:26 # @Author : AnWen from f ...
- NSLog的各种打印格式符和打印CGRect相关结构体
1.打印CG开头的数据类型,如CGRect,CGSize等方法 1.1 打印CGRect : NSLog(@"%@", NSStringFromCGRect(someCGRect) ...
- 微信小程序跑马灯效果--基于CSS3 animation 及 基于JS
如果本文对你有用,请爱心点个赞,提高排名,帮助更多的人.谢谢大家!❤ 如果解决不了,可以在文末进群交流. 基于CSS3主要代码实现 效果图: 视图模板wxml中: <view class=&qu ...
- MySQL Lock--MySQL加锁学习2
准备测试数据: ## 开启InnoDB Monitor SET GLOBAL innodb_status_output=ON; SET GLOBAL innodb_status_output_lock ...
- Spring中抛出异常时,既要要返回错误信息,还要做事务回滚
情况一:如果没有在程序中手动捕获异常,如下代码事务会回滚 情况二:如果在程序中自已捕获异常未往外抛,如下代码事务不会回滚 如果doDbStuff2()这个操作数据库的方法抛出异常,因为将异常捕获未往外 ...
- 2013.4.30 - KDD第十二天
早上来实验室,本来打算向秦师兄要文献的,不过秦师兄上午不在,所以就没有联系他.于是就开始调试郑茂的代码,发现原来那个itoa函数不是标准库里面 的,所以可能只有windows上可以用.然后我就在打电脑 ...
- 2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018)-E. Explosion Exploit-概率+状压dp
2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018)-E. Explosion Exploit-概率+状压dp [P ...
- Django之路——9 Django的form组件的信息校验
forms组件 校验字段功能 针对一个实例:注册用户讲解. 模型:models.py class UserInfo(models.Model): name=models.CharField(max_l ...