Wpf 为什么与usercontrol代码中的属性的相对源绑定失败了?
你可以这样做Wpf 为什么与usercontrol代码中的属性的相对源绑定失败了?,wpf,binding,Wpf,Binding,你可以这样做 public partial class ProjectElementView : UserControl { private string _hello = "hello"; public string Hello { get { return _hello; } set { _hello = value; } } } 编辑 RelativeSource属性用于指定相对于当前对象定位的对象作为源 更多检查 关
public partial class ProjectElementView : UserControl
{
private string _hello = "hello";
public string Hello
{
get { return _hello; }
set { _hello = value; }
}
}
编辑
RelativeSource属性用于指定相对于当前对象定位的对象作为源
更多检查
关键是,我不认为您将能够使用RelativeSource访问非datacotext属性,这两种方法似乎都是有效的
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}, Path=DataContext.Message}" />
或
再次强调,如果不设置datacontext,您无法访问代码隐藏属性。但我建议您将属性移动到viewmodel类并绑定到该类。这将为您提供更大的灵活性
请查看此链接以了解更多信息
仍然不起作用。我想绑定到的prop不在UserControl的datacontext.Ugh中。是同样的事情导致使用ElementName的绑定失败吗?有什么解决办法吗?我想看一下用户控件的完整声明,而不仅仅是菜单项摘录会很有帮助。另外,在VisualStudio的输出窗口中,您应该有绑定错误;你能提供那个文本吗?谢谢。看起来这不像我想象的那么简单。
public partial class ProjectElementView : UserControl
{
private string _hello = "hello";
public string Hello
{
get { return _hello; }
set { _hello = value; }
}
}
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}, Path=DataContext.Message}" />
<UserControl x:Name="sample" >
<Grid>
<TabControl DataContext="{Binding ElementName=sample}" >
<TabControl.ContextMenu>
<ContextMenu >
<MenuItem Header="{Binding Path=Hello}" />
</ContextMenu>
</TabControl.ContextMenu>
</TabControl>
</Grid>
<UserControl>
<Grid>
<TabControl >
<TabControl.ContextMenu>
<ContextMenu >
<MenuItem Header="{Binding Path=Hello}" />
</ContextMenu>
</TabControl.ContextMenu>
</TabControl>
</Grid>