我正在制作一个简单的示例来学习如何创建可绑定的用户控件。我已经创建了一个简单的类:
class Person
{
public string firstName;
public string lastName;
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
以下是一个非常简单的用户控件:
<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>
我想知道的是,我需要做什么才能像使用普通控件一样在上下文中使用用户控件。我可以将其添加到
MainWindow
中:<local:ExampleHRControl x:Name="Hr1"></local:ExampleHRControl>
然后我可以通过代码后台来访问它并添加值:
Hr1.textFirstName.Text = "John";
Hr1.textLasttName.Text = "Doe";
我希望能够创建一个Person
类的实例,并将主窗口上的控件简单地绑定到Person
类。
UserControl
最终会成为一个ContentControl
,那么最好不要更改DataContext
。一个简单的解决方案是给用户控件命名,并通过ElementName
在绑定中引用它。 - user7116