我試圖在WPF中創建一個具有標籤和文本框的可重用UserControl。我想添加屬性到我的UserControl中,以便將兩個子控件的Text字段向上鼓泡,以便於綁定。我讀到我需要通過向DependencyProperties添加所有者來進行一點關注。這是我的代碼現在。它看起來很接近但不完全正確。有任何想法嗎?WPF複合控件
這裏是XAML中:
<UserControl x:Class="MAAD.AircraftExit.Visual.LabelTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="20" Width="300">
<DockPanel>
<TextBlock Text="{Binding Path=Label, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" DockPanel.Dock="Left" TextAlignment="Right" Width="122" />
<TextBlock Text=": " DockPanel.Dock="Left"/>
<TextBox Text="{Binding Path=Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</DockPanel>
</UserControl>
而後面的代碼:
public partial class LabelTextBox : UserControl
{
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(LabelTextBox));
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(LabelTextBox));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(LabelTextBox.TextProperty, value); }
}
public LabelTextBox()
{
InitializeComponent();
ClearValue(HeightProperty);
ClearValue(WidthProperty);
}
}
編輯:這是最後的工作代碼。我切換到相對源綁定。
我在第一次嘗試同樣的事情,以及假設這是什麼所有者的概念是關於。不幸的是,我遇到了同樣的問題,並最終訴諸於綁定。另外,我的非依賴屬性具有用於傳播屬性更改通知的不同自定義解決方案。 – jpierson 2010-03-23 18:57:51