[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.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 on 2019-04-29 00:09 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/10787935.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值