我正在做一个简单的演示来学习如何创建一个可绑定的用户控件。我创建了一个简单的类:如何使自定义XAML用户控件可绑定?
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
类。
不改变'DataContext'可能是有益的,特别是如果这个'UserControl'最终成为'ContentControl'。一个简单的解决方案是命名用户控件并通过'ElementName'在绑定中引用它。 – user7116 2012-04-18 21:32:11
sixlettervariables是正确的。看看这个[解释](http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight /) 由于这个原因。 – LPL 2012-04-18 21:57:05
我已经在上面的原始发布中进行了六个字母变量推荐的更改。 – Curtis 2012-04-19 14:53:01