WPF绑定不到父控件属性

原因:
如果A控件并不是属于visual tree的部分,那么他不能连接到他父控件的datacontext,也就不能绑定到父控件的属性


解决方案:
使用一个Freezable做代理

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

然后在XML文件中添加静态资源,将代理的Data绑定为父控件

    <UserControl.Resources>
        <ResourceDictionary>
            <pubEntity:BindingProxy x:Key="Proxy" Data="{Binding}" />
        </ResourceDictionary>
    </UserControl.Resources>

最后在A控件中,通过静态资源的Data来绑定父控件的属性

Command="{Binding Data.DownLoadCommand,Source={StaticResource Proxy}}"
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值