我正在尝试在WPF中创建一个可重用的UserControl,其中包含一个Label和一个TextBox。我想为我的UserControl添加属性,以便将两个子控件的文本字段上移到父级以便于绑定。我读到需要通过向DependencyProperties添加owner来进行一些操作。这是我的代码。看起来很接近但还不够完美。有什么建议吗?
这是Xaml:
编辑:这是最终可工作的代码。我切换到了相对源绑定。
这是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);
}
}
编辑:这是最终可工作的代码。我切换到了相对源绑定。