原因:
如果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}}"