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:
1
2
3
|
< 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:
1
2
3
4
|
< 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:
1
2
3
4
|
< 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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
:
1
2
3
|
< 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:
1
2
3
4
|
< 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.
项目中我是这样做的:
做一个BindingProxy类
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWsAAAD0CAIAAADSY5ANAAAcAUlEQVR4nO2d7XMbRZ7H959p8RBi4zh2JNuyg5M4RBAUIAlheQwh2AsOyyJxhDzV1cGbdQ7fQcEQqrJ3S0HB4VtvoMqzW4AhDxi8uRdUpeS9d6H2qpyq8CYwf4HvxWhmunu6W63WSDNqfVWfomxppqcl0h9P92h+31+Nj09u3ny3z+BgfnAwH/5KSK5jfPPN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urfazrR9yz2KbQZD2EKejBmmtcVHVohaAQdqPbQYhSHsIuxG0WdEzSLwpYfFxZiokykyQ95CroxEvay6qPCzuYTxLoWG2gzpowlO8BWEHujGZoR1YaBCCtAd5iS1ZJxWxCVFBZp3MhHgRMEUAAteyom5oo6Y0sh1EQRPiBsUGsSCZoR3YaRCkPcjKfEqekcc71MuLqaqEcSup0orthK20Gm9ZZRDtLAVptoM6aILZUWQQG5IZ2oGFBkHagyKsQNxJ+eFIOB3gtpeug1B/zFXly0UtKwyiXwldWle5YZn4qG8Cg4j71mXJDO3ANoMg7UEdViDuZOPpA9tPdcXzcAw3MgjfsqJ2eUYNEh7RU3yAdmObQZD2oA4rED+jGLrRMqVyFsO3JnkX8VlMvAyycA6on6WgaRBl3wQGsSKZoR0wBikWdxSL3W0QpD0Qo5VURWyCeCVVWuQ9vlQsDUAQtMydr5Ho+yAGWQpsPxsFTdSYDzauaQuSGdqBVQZB2kPwvDSsINor9qc+3hRjIkZwysyE+FUe0buQtMx2nrVJ81kKdD8Fg1zSoPREr9uTGdqBPQZB2gMAnccegwAAOg8MAgAwBwYBAJgDgwAAzIFBAADmwCAAAHNgEACAOTAIAMAcGAQAYA5nkJ3F4s5UDLJr11TbGielUunYsWNV6lEoFPRvdQEAyPh/BD4ZNIWN1s4AAAAASUVORK5CYII=" alt="" width="276" height="185" />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows; namespace Halliburton.Castor.Controls
{
class BindingProxy : Freezable
{
#region Overrides of Freezable protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
} #endregion public object DataContextData
{
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("DataContextData", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
}
<ControlTemplate x:Key="DataGridForOilSwell_Template">
<DataGrid x:Name="datagrid"
Margin="10,0"
VerticalAlignment="Top"
AutoGenerateColumns="False"
Background="#FFD1D2D4"
CanUserAddRows="False"
CanUserReorderColumns="False"
CanUserResizeColumns="False"
CellStyle="{StaticResource DataGrid_Cell_Style}"
HorizontalScrollBarVisibility="Disabled"
IsReadOnly="True"
ItemsSource="{Binding ResultItems}"
RowHeaderWidth="0"
RowStyle="{StaticResource DataGrid_Row_Style}"
ScrollViewer.CanContentScroll="False"
Style="{StaticResource DataGridStyle}">
<DataGrid.Resources>
<controls:BindingProxy x:Key="proxy" DataContextData="{Binding}" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Width="*"
MinWidth="115"
CellTemplate="{StaticResource RubberTypeRow_DataTemplate}"
HeaderStyle="{StaticResource DataGrid_ColumnHeader_Style}"
HeaderTemplate="{StaticResource DesignNameHeader_DataTemplate}" /> <DataGridTemplateColumn Width="*"
MinWidth="90"
CellTemplate="{StaticResource VolumeHoleIDRow_DataTemplate}"
HeaderStyle="{StaticResource DataGrid_ColumnHeader_Style}"
HeaderTemplate="{StaticResource VolumeHoleIDHeader_DataTemplate}" /> <DataGridTemplateColumn x:Name="AvgPackerTempColumn"
Width="*"
MinWidth="60"
CellTemplate="{StaticResource AvgPackerTempRow_DataTemplate}"
HeaderStyle="{StaticResource DataGrid_ColumnHeader_Style}"
HeaderTemplate="{StaticResource AvgPackerTempHeader_DataTemplate}"
Visibility="{Binding DataContextData.IsStimulation,
Source={StaticResource proxy},
Converter={StaticResource boolToVisibilityConverter}}" />
<DataGridTemplateColumn x:Name="DeltaTempColumn"
Width="*"
MinWidth="60"
CellTemplate="{StaticResource DeltaTempRow_DataTemplate}"
HeaderStyle="{StaticResource DataGrid_ColumnHeader_Style}"
HeaderTemplate="{StaticResource DeltaTempHeader_DataTemplate}"
Visibility="{Binding DataContextData.IsStimulation,
Source={StaticResource proxy},
Converter={StaticResource boolToVisibilityConverter}}" />
......
How to bind to data when the DataContext is not inherited【项目】的更多相关文章
- [WPF] How to bind to data when the datacontext is not inherited
原文:[WPF] How to bind to data when the datacontext is not inherited 原文地址:http://www.thomaslevesque.co ...
- jquery方法详解--bind(type, [data], fn)
转自:http://www.zhufengpeixun.cn/jquery/bind_type_data_fn.html bind(type, [data], fn) 返回值::jQuery 概述 ...
- Spring mvc Data Redis—Pub/Sub(附Web项目源码)
一.发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候,我们称这个客户端为发布者(publisher). 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE ...
- Spring Data Redis—Pub/Sub(附Web项目源码)
一.发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候,我们称这个客户端为发布者(publisher). 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE ...
- Spring Data Redis—Pub/Sub(附Web项目源码) (转)
一.发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候,我们称这个客户端为发布者(publisher). 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE ...
- datagrid其中某列需要动态隐藏或显示的mvvm绑定方式,也可以用在其他表格类型控件上
版权归原作者所有. 引用地址 [WPF] HOW TO BIND TO DATA WHEN THE DATACONTEXT IS NOT INHERITED MARCH 21, 2011 THOMAS ...
- Data Binding in WPF
http://msdn.microsoft.com/en-us/magazine/cc163299.aspx#S1 Data Binding in WPF John Papa Code downl ...
- WPF之DataContext(转)
WPF之DataContext(转) 有时候不是你不够聪明,而是别人教给你的东西太烂!相信自己! 这是我认为,目前网络上对“DataContext”解释最好的一篇文章,跟大家分享. 原文地址:http ...
- How to bind a Command on a ContextMenu within a DataTemplate using MVVM
Since the Popuup control has it's separate visual tree, you cannot use find ancestor to find the Gri ...
随机推荐
- 【英语】Bingo口语笔记(34) - Hit系列
hit it off 合得来 hit the bottle 喝醉酒 hit the spot 正合要求,恰到好处
- [转]glew, glee与 gl glu glut glx glext的区别和关系
原文地址:http://blog.csdn.net/delacroix_xu/article/details/5881942 因为也是初接触,所以就当了解,等深入学习后再回顾这篇文章观点. GLEW是 ...
- 分享15款为jQuery Mobile定制的插件
jQuery Mobile 1.0 已经发布了, 做为jQuery的移动设备类库, 并且依靠着jQuery这个及其受欢迎的类库,必将带给大家不一样的使用体验,基于jQuery Mobile的插件开发必 ...
- centos下安装eclipse-c++
eclipse-c++ 1)编译器及工具链 yum install gcc gcc-c++ 2)开发工具包(JDK):下载网址:http://www.oracle.com/technetwork/ja ...
- C# 对Excel 单元格格式, 及行高、 列宽、 单元格边框线、 冻结设置
一.对行高,列宽.单元格边框等的设置 这篇简短的文字对单元格的操作总结的比较全面,特此转载过来. private _Workbook _workBook = null; private Workshe ...
- [Everyday Mathematic]20150213
设 $f:\bbR\to\bbR$ 三阶可微, 试证: 存在 $\xi\in (-1,,1)$, 使得 $$\bex \frac{f'''(\xi)}{6}=\frac{f(1)-f(-1)}{2}- ...
- UML系列图------用例图介绍
UML-Unified Model Language 统一建模语言,又称标准建模语言.是用来对软件密集系统进行可视化建模的一种语言. 在UML系统开发中有三个主要的模型: 功能模型: 从用户的角度展示 ...
- iOS学习笔记之回调(二)
写在前面 上一篇学习笔记中简单介绍了通过目标-动作对实现回调操作:创建两个对象timer和logger,将logger设置为timer的目标,timer定时调用logger的sayOuch函数.在这个 ...
- coroutine in c 备忘
coroutine: stackless和stackful jmp 基于switch的trick: http://www.chiark.greenend.org.uk/~sgtatham/corout ...
- 【quick-cocos2d-x】Lua 语言基础
版权声明:本文为博主原创文章,转载请注明出处. 使用quick-x开发游戏有两年时间了,quick-x是cocos2d-Lua的一个豪华升级版的框架,使用Lua编程.相比于C++,lua的开发确实快速 ...