如何在WPF中实现与用户控件的数据绑定?

2023-12-25

我对 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 接口,但没有帮助。


你想要绑定Text你的 TextBox 的属性返回到TheText它所在的 UserControl 的属性,对吗?因此,您需要告诉绑定该属性所在的位置。有几种方法可以做到这一点(您可以使用 FindAncestor 使用relativesource 来完成此操作),但最简单的方法是在 XAML 中为 UserControl 指定一个“名称”并使用元素绑定进行绑定:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在WPF中实现与用户控件的数据绑定? 的相关文章

随机推荐