您的位置:首页 > 其它

WPF绑定不到父控件属性

2018-03-07 17:03 519 查看
原因:

如果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}}"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  WPF 绑定 父控件