ヘッダー ラベルと 2 つのボタンを定義する複数のページで使用しているユーザー コントロールがあります。コントロールが子コントロールを持つことができるようにしたいのですが、アイテムコレクションにあるため、それらの子コントロールをバインドするという問題に遭遇しました。XAML で子コントロールにバインドを追加すると、それらは登録されません。
エラー出力:System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=MyPage'. BindingExpression:Path=MyText; DataItem=null; target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')
簡潔にするために、余分なコードは省略されています。
例えば
XAML
<UserControl x:Class="MyControl" Name="MyControl">
<Grid>
<ItemsControl Name="ItemsControl" ItemsSource="{Binding ItemsSource, ElementName=MyControl}" />
</Grid>
</UserControl>
コードビハインド
[ContentProperty("Items")]
public partial class MyControl : UserControl
{
public static readonly DependencyProperty ItemsSourceProperty =
ItemsControl.ItemsSourceProperty.AddOwner(typeof (MyControl));
public IEnumerable ItemsSource
{
get { return (IEnumerable) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public ItemCollection Items
{
get { return ItemsControl.Items; }
}
}
使用法:
<Page x:Class="MyPage" Name="MyPage">
<MyControl>
<TextBox Text="{Binding MyText,
ElementName=MyPage,
UpdateSourceTrigger=PropertyChanged}" />
</MyControl>
</Page>
コードビハインド
public partial class MyPage : Page, INotifyPropertyChanged
{
private string _myText;
public string MyText
{
get{ return _myText; }
set
{
_myText = value;
OnPropertyChanged("MyText");
}
}
}
TextBox をMyText
プロパティにデータバインドできるようにして、背後のコードで変更するたびにページで更新されるようにしたいと考えています。