Windows 8 ストア アプリ (Metro / Modern?) を作成しており、複数のフォームで書式設定を再利用するためのコントロールを作成しています。過去にいくつかの WPF アプリを作成しましたが、WPF で行ったのと同じ方法で依存関係プロパティを作成しようとしました。コントロールをフォームに配置して使用すると、値が返されません。
私の personControl.cs WPF クラス:
public partial class PersonControl : UserControl {
public PersonControl()
{
InitializeComponent();
}
public static readonly DependencyProperty PersonProperty =
DependencyProperty.Register("thisPerson", typeof(Person), typeof(PersonControl));
public Person thisPerson
{
get
{
return (Person)GetValue(PersonProperty);
}
set
{
SetValue(PersonProperty, value);
}
}
}
Windows 8アプリの場合、PropertyMetadataを追加する必要があります-これが私が間違っているところだと思いますが、代わりに何をすべきかを追跡できませんでした:
パブリック部分クラス PersonControl : UserControl {
public PersonControl()
{
InitializeComponent();
}
public static readonly DependencyProperty PersonProperty =
DependencyProperty.Register("thisPerson", typeof(Person), typeof(PersonControl), new PropertyMetadata(new Person()));
public Person thisPerson
{
get
{
return (Person)GetValue(PersonProperty);
}
set
{
SetValue(PersonProperty, value);
}
}
}
私が知っている XAML でのコントロールの使用法またはバインディングに変更はありません。私はまだサンプルデータを使用しているので、List(Person) を作成してからリストボックスを作成し、リストボックスを List(Person) にバインドします。
バインディングコードは次のとおりです。
ユーザーコントロールの xaml で:
<Grid x:Name=”PersonGrid”>
…….
<TextBox x:Name="txtFirstName" Text="{Binding Path=thisPerson.FirstName, ElementName=This}"></TextBox>
メインページ Xaml:
<StackPanel x:Name="layoutRoot">
<ListBox x:Name="myListbox">
<ListBox.ItemTemplate>
<DataTemplate>
<local:PersonControl x:Name="myControl" thisPerson="{Binding Path=.}" Margin="5"></local:PersonControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
メインページのコードビハインド:
List<Person> People = new List<Person>();
… populate data …
myListbox.ItemsSource = People;
追加のメモとして、UserControlXaml のコンテンツを取得し、UI 要素をメイン ページの XAML に直接配置すると、正常に動作します。失敗するのは、UserControl を使用するときです。