【发布时间】:2012-12-17 14:31:36
【问题描述】:
我有一个跨多个页面使用的用户控件,它定义了一个标题标签和两个按钮。我希望控件能够拥有子控件,但是我遇到了绑定这些子控件的问题,因为它们位于 itemscollection 中。当我将绑定添加到 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 属性,这样每当我在后面的代码中修改它时,它就会在页面上得到更新。
【问题讨论】:
-
这不是问题。你现在有什么问题?你有什么例外吗?它没有按预期工作吗?您得到的实际行为与您期望的行为是什么?
-
另外,你的
DependencyObject派生类不应该实现INotifyPropertyChanged。 -
@HighCore 预期的功能是将文本框绑定到 MyPage 的 MyText 属性。实际结果是什么都没发生。
-
查看 Visual Studio 输出窗口是否有绑定错误。