gpt4 book ai didi

c# - 如何在 WPF 中实现与用户控件的数据绑定(bind)?

转载 作者:太空狗 更新时间:2023-10-30 01:28:14 24 4
gpt4 key购买 nike

我是 WPF 的新手,我在让数据绑定(bind)按我的意愿工作时遇到了一些问题。我编写了一个用户控件,其中包含一个 TextBox,我想将其 Text-Property 绑定(bind)到我的 UserControl 的一个属性,我想再次将其绑定(bind)到其他东西。

我错过了什么?

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 接口(interface),但没有帮助。

最佳答案

您想将 TextBox 的 Text 属性绑定(bind)回它所在的 UserControl 的 TheText 属性,对吗?所以你需要告诉绑定(bind)属性所在的位置。有几种方法可以做到这一点(您可以使用 FindAncestor 通过 RelativeSource 来做到这一点)但最简单的方法是在 XAML 中为 UserControl 提供一个“名称”并使用元素绑定(bind)进行绑定(bind):

<UserControl ...
x:Name="me" />
<TextBox Text="{Binding TheText,ElementName=me}" />
</UserControl>

现在您的 TextBox 将反射(reflect)您分配(或绑定(bind))到“SomeControl.TheText”属性的值 - 您无需更改任何其他代码,尽管您可能希望在底层实现 INotifyPropertyChanged MyClass 对象,以便绑定(bind)知道属性何时更改。

关于c# - 如何在 WPF 中实现与用户控件的数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1192100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com