I have a user control that I’m using across several pages which defines a header label and two buttons. I want the control to be able to have child controls, but I ran into the problem of binding those child controls since they are in an itemscollection. When I add bindings to the child controls in XAML they are not registered.
Error output: 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')
Excess code omitted for brevity.
e.g.
XAML
<UserControl x:Class="MyControl" Name="MyControl">
<Grid>
<ItemsControl Name="ItemsControl" ItemsSource="{Binding ItemsSource, ElementName=MyControl}" />
</Grid>
</UserControl>
Code Behind
[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; }
}
}
Usage:
<Page x:Class="MyPage" Name="MyPage">
<MyControl>
<TextBox Text="{Binding MyText,
ElementName=MyPage,
UpdateSourceTrigger=PropertyChanged}" />
</MyControl>
</Page>
Code Behind
public partial class MyPage : Page, INotifyPropertyChanged
{
private string _myText;
public string MyText
{
get{ return _myText; }
set
{
_myText = value;
OnPropertyChanged("MyText");
}
}
}
I would like to be able to databind the TextBox to the MyText property so that whenever I modify it in the code behind it will get updated on the page.
Converting my comment into an answer:
remove the
ElementNameand tryRelativeSource={RelativeSource FindAncestor, AncestorType=Page}