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

标签 c# wpf data-binding xaml user-controls

我是 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/

相关文章:

c# - ASP.NET MVC - 模型接口(interface)

C# - SQL - LINQ 查询

wpf - 更改项目控件中选项卡项目的不透明度

WPF XAML x :Name ="[Anything]" causes compilation to fail with "Type ' MyType' is not defined"

wpf datagrid 单元格背景颜色未完全填充

c# - DataAdapter Fill 没有从 Command 对象获取参数

c# - 在不更改所选项目的情况下聚焦 wpf 列表框

c# - 函数返回时出现 NullReferenceException

c# - C#中 "this"是什么意思

c# - 数据网格单元格行点击事件