由DataGridTextColumn不能获取到父级DataContext引发的思考
在项目中使用DataGrid需要根据业务动态隐藏某些列,思路都是给DataGrid中列的Visibility属性绑定值来实现(项目使用MVVM),如下
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Visibility="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}},Path=DataContext.IsVisible,Converter={StaticResource BooleanToVisibilityConverter}}"></DataGridTextColumn>
如果不是在DataGridTextColumn上绑定,那么这段代码是可以工作的,问题出在DataGridTextColumn上,我们来看它的继承层次
它不是FrameworkElement的派生类,所以它不具有DataContext属性,也就是说,即使DataGrid有DataContext,DataGridTextColumn也不能得到它,Visibility找不到DataContext自然绑定不上,这就是为什么上面的绑定失效的原因,同样其他类型的列也有同样的问题。那么如何优雅地解决问题呢?国际友人给出了这样一个方法,既然DataGridTextColumn不能从父级那里得到DataContext,那么直接给她的Visibility指定一个DataContext,实现如下
- 首先创建一个可以承载DataContext的绑定代理类BindingProxy
- 然后将这个BindingProxy当作资源,获得DataContext
- 将DataGridTextColumn的Visibility的DataContext指定为这个BindingProxy
BindingProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows; namespace WPF_DataContext_Sample
{
public class BindingProxy:Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy(); } public object DataContext
{
get
{
return (object)GetValue(DataContextProperty);
}
set
{
SetValue(DataContextProperty, value);
}
} // Using a DependencyProperty as the backing store for DataContext. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataContextProperty =
DependencyProperty.Register("DataContext", typeof(object), typeof(BindingProxy), new PropertyMetadata(null));
}
}
MainWindow.xaml
<Window x:Class="WPF_DataContext_Sample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfDataContextSample="clr-namespace:WPF_DataContext_Sample"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<wpfDataContextSample:Converter x:Key="Converter"></wpfDataContextSample:Converter> <wpfDataContextSample:BindingProxy x:Key="BindingProxy" DataContext="{Binding}"></wpfDataContextSample:BindingProxy>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="0.1*"/>
</Grid.RowDefinitions>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Students}">
<DataGrid.Columns> <DataGridTextColumn Header="Id" Binding="{Binding Id}"></DataGridTextColumn> <!--这样的绑定会失败-->
<!--<DataGridTextColumn Header="Name" Binding="{Binding Name}" Visibility="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}},Path=DataContext.IsShow,Converter={StaticResource BooleanToVisibilityConverter}}"></DataGridTextColumn>--> <DataGridTextColumn Header="Name" Binding="{Binding Name}" Visibility="{Binding DataContext.IsShow,Source={StaticResource BindingProxy},Converter={StaticResource Converter}}"></DataGridTextColumn> <DataGridTextColumn Header="Sex" Binding="{Binding Sex}"></DataGridTextColumn> </DataGrid.Columns>
</DataGrid> <StackPanel Orientation="Horizontal" Grid.Row="1">
<Button Width="100" Height="30" Content="隐藏Name" Click="ButtonBase_OnClick"></Button>
</StackPanel>
</Grid>
</Window>
这样就能优雅地解决了这个问题
Demo:WPF_DataContextAndDataGridTextColumn_Sample.rar
由DataGridTextColumn不能获取到父级DataContext引发的思考的更多相关文章
- Java IO,io,文件操作,删除文件,删除文件夹,获取文件父级目录
Java IO,io,文件操作,删除文件,删除文件夹,获取文件父级目录 这里先简单的贴下常用的方法: File.separator //当前系统文件分隔符 File.pathSeparator // ...
- jQuery获取所有父级元素及同级元素及子元素的方法
jQuery获取所有父级元素及同级元素及子元素的方法 1.获取父级元素 $("#id").parent() 获取其父级元素 $("#id").parents() ...
- mysql获取子父级节点
获取所有子节点 DROP FUNCTION IF EXISTS `F_Co29_GetAllChildrenIdsOfTaskevent`;DELIMITER //CREATE FUNCTION `F ...
- SQL根据指定节点ID获取所有父级节点和子级节点
--根据指定节点ID获取所有子节点-- WITH TEMP AS ( SELECT * FROM table_name WHERE Id=' --表的主键ID UNION ALL SELECT T0. ...
- SQL根据指定节点ID获取所有父级节点和子级节点(转载)
--根据指定节点ID获取所有子节点-- WITH TEMP AS ( ' --表的主键ID UNION ALL SELECT T0.* FROM TEMP,table_name T0 WHERE TE ...
- el-tree点击获取直接父级的属性
这里是可以一直往上获取它的直接父级的所有属性以及状态 通过这两个事件其中的一个 在方法里可以写上 methods:{ curCheck(data,state){ const curNode = thi ...
- mysql oracle sql获取树 父级 子级 及自己
select * from ( select t.*,d.TABLE_NAME,d.QUERY_SQL,d.data_control_col,d.id table_id,d.where_sql fro ...
- jQuery使用(四):DOM操作之查找兄弟元素和父级元素
查找兄弟元素 向下查找兄弟元素 next() nextAll() nextUntil() 向上查找兄弟元素 prev() prevAll() prevUntil() 查找所有兄弟元素 siblings ...
- js动态绑定class(当前父级div下的子元素有没有这个class,有的话移除,没有的话添加)
<div class="layui-inline" id=‘’ onclick="changeType(id)"> ...
随机推荐
- Error during installing HAXM, VT-X not working 在安装HAXM错误,开始不工作
最佳答案 (Best Answer) Some antivirus options prevent Haxm installation. ie: Avast : settings (parametre ...
- 探索 OpenStack 之(12):cinder-api Service 处理 HTTP Request 的过程分析
本文是上一篇 探索 OpenStack 之(11):cinder-api Service 启动过程分析 以及 WSGI / Paste deploy / Router 等介绍> 的后续篇. os ...
- dipole antenna simulation by CST
CST偶极子天线仿真,半波振子天线 一.本文使用CST仿真频率为1GHz的偶极子天线,使用2013版本.仿真的步骤为 1.选择一个CST的天线工程模板 2.设置好默认的单位 3.设置背景的材料(空气腔 ...
- NOIP2010普及组 三国游戏 -SilverN
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> usin ...
- [转]Javascript中的自执行函数表达式
[转]Javascript中的自执行函数表达式 本文转载自:http://www.ghugo.com/javascript-auto-run-function/ 以下是正文: Posted on 20 ...
- 写一个iOS VoIP应用需要知道什么?
IOS编程--VoIP解密 一般来说, IOS很少给App后台运行的权限. 仅有的方式就是 VoIP. IOS少有的为VoIP应用提供了后台socket连接,定期唤醒并且随开机启动的权限.而这些就是I ...
- 边工作边刷题:70天一遍leetcode: day 86-2
Best Meeting Point 要点: 题本身不难理解,manhattan distance.follow up就变成weighted了(因为一个地方可以有多个住户) 注意input是grid的 ...
- HDU 4998 Rotate --几何
题意:给n个点(x,y,p),从1~n,一次每次所有点绕着第 i 个点(原来的)逆时针转pi个弧度,问最后所有点的位置相当于绕哪个点旋转多少弧度,求出那点X和弧度P 解法:直接模拟旋转,每次计算新的坐 ...
- 通过JDBC进行简单的增删改查(二)
本章笔记更易理解和学习,也是我第一次初学的笔记. package javastudy; import java.sql.Connection; import java.sql.DriverManage ...
- CLOSE_WAIT?项目上线之际遇到这样的烦心事
项目内测中,马上就要发布了,如今内测,所以很忙,今天运维那发来一堆状态,忘记截图了,简单来讲就是HTTP发送请求的时候有连接等待关闭,导致CLOSE_WAIT这个状态一直累加,没有释放,这样长时间下去 ...