现在发现一个问题,如果在xaml中某个控件的属性通过ElementName绑定了。
大概代码如下:
/// <summary>
/// 输入点名字
/// </summary>
public string Title
{
get { return (string)GetValue(PointInputStyleProperty); }
set { SetValue(PointInputStyleProperty, value); }
}
public static readonly DependencyProperty PointInputStyleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(UserControl1), new PropertyMetadata(pointinputstyle));
xaml如下:
<Label Content="{Binding ElementName=UserControl1,Path=Title,Mode=OneWay}" Style="{StaticResource sadfstyle}"/>
此时,如果通过DataContext绑定后,发现绑定是无效的。原因分析如下:
1、使用了ElementName后,扎到的是当前这个控件自己的属性,也就是上面定义的那个Title属性,找到的不是DataContext里面的的Title了。
如果此时改成了
<Label Content="{Binding Title,Mode=OneWay}" Style="{StaticResource sadfstyle}"/>
此时就找不到了当前控件定义的Title属性了,只会找到绑定的DataContext里面的数据了
------------------------------------------------------------------------------------------------------------------------
2018-11-21
上面虽然解决比较不尽人意,实际使用也出现了一些问题。最近在《WPF编程宝典》中终于找到了最终的解决方案;
<Label Height ="50" Width="100" Background="Green" Content="{Binding Path=Title,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Mode=TwoWay}"></Label>
使用了RelativeSource进行相对的绑定,完美解决。
扫描二维码关注公众号,回复:
4723260 查看本文章