WPF的DataContext传递性,的确很是好用。可是在某些特定的环境下,元素并不能从视觉树(VisualTree)向上获取传递,好比未指定数据源和Popup性质的浮动层,特别是菜单功能。布局
一些简单的地方,好比你作数据绑定,若是你有一个ViewModel,内部有学生列表,同时还备好了一个ICommand,每个学生项想直接调用这个ICommand是不可行的,通常是经过两种方式获取到ViewModel,以后再绑定ICommand。方法1是获取ElementName而后读取控件的DataContext。第二种方式是使用RelativeSource获取上级控件的数据源。这两种方法都有局限性,布局改变影响大,甚至写法怪异。spa
有一个很好的方法那就是,先把可能用到的数据,做为资源,咱们先备好一个容器存着。code
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)); }
资源的定义也是比较简单的,在适当的位置,准备好你的数据源。blog
<DataGrid.Resources> <local:BindingProxy x:Key="proxy" Data="{Binding}" /> </DataGrid.Resources>
最后,在须要引用数据的地方,执行绑定。资源
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False" Visibility="{Binding Data.ShowPrice, Converter={StaticResource visibilityConverter}, Source={StaticResource proxy}}"/>