wpf 自定義控制元件中ElementName和DataContext之間的衝突
阿新 • • 發佈:2018-12-31
現在發現一個問題,如果在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進行相對的繫結,完美解決。