[WPF] How to bind to data when the datacontext is not inherited

原文地址:http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

WPF的DataContext传递性,的确非常好用。但是在某些特定的环境下,元素并不能从视觉树(VisualTree)向上获取传递,比如未指定数据源和Popup性质的浮动层,特别是菜单功能。

一些简单的地方,比如你做数据绑定,如果你有一个ViewModel,内部有学生列表,同时还备好了一个ICommand,每一个学生项想直接调用这个ICommand是不可行的,一般是通过两种方式获取到ViewModel,之后再绑定ICommand。方法1是获取ElementName然后读取控件的DataContext。第二种方式是使用RelativeSource获取上级控件的数据源。这两种方法都有局限性,布局改变影响大,甚至写法怪异。

有一个很好的方法那就是,先把可能用到的数据,作为资源,我们先备好一个容器存着。

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));
}

资源的定义也是比较简单的,在适当的位置,准备好你的数据源。

<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}}"/>

 

posted @ 2017-12-22 16:30  三台  阅读(295)  评论(0编辑  收藏  举报