我正在制作一个简单的演示来学习如何创建一个可绑定的用户控件.我创建了一个简单的类:
class Person
{
public string firstName;
public string lastName;
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
Run Code Online (Sandbox Code Playgroud)
而且一个非常简单的用户控件:
<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>
Run Code Online (Sandbox Code Playgroud)
我想知道的是,为了能够像普通控件一样在上下文中使用用户控件,我需要做什么.我可以添加到MainWindow:
<local:ExampleHRControl x:Name="Hr1"></local:ExampleHRControl>
Run Code Online (Sandbox Code Playgroud)
然后我可以通过后面的代码解决它并添加值:
Hr1.textFirstName.Text = "John";
Hr1.textLasttName.Text = "Doe";
Run Code Online (Sandbox Code Playgroud)
我希望能够创建类的实例,Person并简单地将主窗口上的控件绑定到Person类.
要完成这项工作,您需要做几件事.
在您的代码隐藏中,为您希望控件了解的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); }
}
Run Code Online (Sandbox Code Playgroud)
在XAML中,将代码隐藏设置为数据上下文,并将绑定添加到person对象:
<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>
Run Code Online (Sandbox Code Playgroud)
现在,只要设置了Person属性,您的控件就会使用与Person关联的First和Last名称进行更新.