私は簡単なデモを作成して、バインド可能なユーザーコントロールを作成する方法を学習しています。私が知りたいのですが、私は、ユーザーが使用できるようにするために何をすべきかが必要ですされカスタム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">
<Grid>
<TextBlock x:Name="textFirstName"></TextBlock>
<TextBlock x:Name="textLastName"></TextBlock>
</Grid>
</UserControl>
:
class Person
{
public string firstName;
public string lastName;
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
、非常にシンプルなユーザーコントロール:私は、単純なクラスを作成しました通常の制御のようなコンテキストでの制御。
<local:ExampleHRControl x:Name="Hr1"></local:ExampleHRControl>
をし、私は背後にあるコードを、それに対処し、値を追加することができます:私はMainWindow
にこれを追加することができます
Hr1.textFirstName.Text = "John";
Hr1.textLasttName.Text = "Doe";
私はクラスPerson
のインスタンスを作成することができることを好むだろうメインウィンドウのコントロールをPerson
クラスにバインドするだけです。
特にこの 'UserControl'が' ContentControl'である場合、 'DataContext'を変更しない方が有益でしょう。これに対する簡単な解決策は、ユーザコントロールに名前を付けて、それを 'ElementName'を介してバインディングで参照することです。 – user7116
6文字の変数が正しい。これを見てください[説明](http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight /) その理由のために。 – LPL
私は上記のオリジナルの投稿で6桁の文字の変更を推奨しました。 – Curtis