I am trying to create a multi-user UserControl in WPF with a shortcut and a text box. I want to add properties to my UserControl to bubble the Text fields of both child controls to the parent for easy binding. I read that I need to focus a bit by adding DependencyProperties owners. Here is my code now. It seems close, but not quite right. Any ideas?
Here is 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>
And the code behind:
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); } }
Edit: Here is the final working code. I switched to relative source binding.
c # data-binding wpf
Jake pearson
source share