[英]How to achieve databinding with a user control in WPF?
我是WPF的新手,我在使用数据绑定工作时遇到了一些问题。 我编写了一个用户控件,其中包含一个TextBox,我的Text-Property要绑定到UserControl的属性,我想再绑定到其他东西。
我错过了什么?
XAML
<!-- User Control -->
<TextBox Text="{Binding Path=TheText}" />
<!-- Window -->
<WpfApplication1:SomeControl TheText="{Binding Path=MyStringProp}" />
C#
// User Control ----
public partial class SomeControl : UserControl
{
public DependencyProperty TheTextProperty = DependencyProperty
.Register("TheText", typeof (string), typeof (SomeControl));
public string TheText
{
get
{
return (string)GetValue(TheTextProperty);
}
set
{
SetValue(TheTextProperty, value);
}
}
public SomeControl()
{
InitializeComponent();
DataContext = this;
}
}
// Window ----
public partial class Window1 : Window
{
private readonly MyClass _myClass;
public Window1()
{
InitializeComponent();
_myClass = new MyClass();
_myClass.MyStringProp = "Hallo Welt";
DataContext = _myClass;
}
}
public class MyClass// : DependencyObject
{
// public static DependencyProperty MyStringPropProperty = DependencyProperty
// .Register("MyStringProp", typeof (string), typeof (MyClass));
public string MyStringProp { get; set; }
// {
// get { return (string)GetValue(MyStringPropProperty); }
// set { SetValue(MyStringPropProperty, value); }
// }
}
最好的祝福
奥利弗哈纳皮
PS:我试图在我的用户控件上实现INotifyPropertyChanged接口,但它没有帮助。
您希望将TextBox的Text
属性绑定回TheText
在的UserControl的TheText
属性,对吧? 所以你需要告诉绑定财产所在的位置。 有几种方法可以做到这一点(您可以使用FindAncestor使用RelativeSource),但最简单的方法是在XAML中为UserControl指定一个“名称”并使用元素绑定进行绑定:
<UserControl ...
x:Name="me" />
<TextBox Text="{Binding TheText,ElementName=me}" />
</UserControl>
现在,您的TextBox将反映您为“SomeControl.TheText”属性指定(或绑定)的值 - 您不需要更改任何其他代码,尽管您可能希望在底层MyClass对象上实现INotifyPropertyChanged绑定知道属性何时发生了变化。
马特为您的问题提供了解决方案。 这是一个更多的解释和暗示将来阻止这个问题。
由于SomeControl.DataContext
是在SomeControl
构造函数中设置的,因此窗口的绑定TheText="{Binding Path=MyStringProp}"
具有SomeControl
类型的Source
,而不是您想要的MyClass
。
在运行时失败的任何绑定都会将调试消息记录到Visual Studio的输出面板中。 在这种情况下,你会发现在'SomeControl'类型的对象上不存在这样的属性'MyStringProp',这应该引起你的怀疑。
我想每个人都发现WPF数据绑定需要一些时间来学习,特别是调试,但坚持不懈。 WPF中的数据绑定非常棒,我仍然知道如何轻松地使我的UI上的数据保持最新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.