How can you customize your XAML control?

I am doing a simple demo to learn how to create a managed user control. I 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 I need to do to be able to use a user control in context, like a regular control. I can add this to MainWindow:

<local:ExampleHRControl x:Name="Hr1"></local:ExampleHRControl>

and then I can access it through the code and add the value:

Hr1.textFirstName.Text = "John";
Hr1.textLasttName.Text = "Doe";

I would prefer to instantiate the class Personand just bind the control in the main window to the class Person.

+5
source share
2 answers

, , .

Person, , :

   public static readonly DependencyProperty PersonProperty =
                          DependencyProperty.Register("Person", typeof(Person),
                                                      typeof(ExampleHRControl));

   public Person Person
   {
      get { return (Person)GetValue(PersonProperty); }
      set { SetValue(PersonProperty, value); }
   }

XAML :

<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>

, Person , First Last, Person.

+5

Dependancy, xaml.
1 -

public static readonly DependencyProperty FirstNameProperty = 
    DependencyProperty.Register(
    "FirstName", typeof(Strin),

2 -

public String FirstName
{
    get { return (String)GetValue(FirstNameProperty); }
    set { SetValue(FirstNameProperty, value); }
}

3- XAML

<local:YourControlName FirstName="john"/>

<local:YourControlName FirstName="{Binding MyFirstName}"/>
+2

All Articles