How do you make a custom XAML User Control bindable?
c#, wpf, xaml
Solution
A couple things you need to do to make this work.
In your code-behind, add a dependency property for the Person object you want your control to know about:
public static readonly DependencyProperty PersonProperty =
DependencyProperty.Register("Person", typeof(Person),
typeof(ExampleHRControl));
public Person Person
{
get { return (Person)GetValue(PersonProperty); }
set { SetValue(PersonProperty, value); }
}
In your XAML, set up your code-behind as your data context and add the binding to your person object:
<UserControl x:Class="Example.ExampleHRControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="This">
<Grid>
<TextBlock x:Name="{Binding Path=Person.FirstName, ElementName=This}"/>
<TextBlock x:Name="{Binding Path=Person.LastName, ElementName=This}"/>
</Grid>
</UserControl>
Now, whenever the Person property is set, your control will update itself with the First and Last names that are associated to the Person.
Problem
I am making a simple demo to learn how to create a bindable user control. I have created a simple class: ``` class Person { public string firstName; public string lastName; public Person(string first, string last) { firstName = first; lastName = last; } } ``` And a very simple user control: ``` <UserControl x:Class="Example.ExampleHRControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <TextBlock x:Name="textFirstName"></TextBlock> <TextBlock x:Name="textLastName"></TextBlock> </Grid> </UserControl> ``` What I would like to know is what do I need to do in order to be able to use the user control in context like a normal control. I can add this to the `MainWindow`: ``` <local:ExampleHRControl x:Name="Hr1"></local:ExampleHRControl> ``` and then I can address it through code behind and add the value: ``` Hr1.textFirstName.Text = "John"; Hr1.textLasttName.Text = "Doe"; ``` I would prefer to be able to create an instance of the class `Person` and simply bind the control on the main window to the `Person` class.