代码之家  ›  专栏  ›  技术社区  ›  Oliver Hanappi

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

  •  4
  • Oliver Hanappi  · 技术社区  · 15 年前

    我对WPF还比较陌生,在让数据绑定按我想要的方式工作时遇到了一些问题。我已经编写了一个用户控件,其中包含一个文本框,我希望将其文本属性绑定到我的用户控件的属性,我希望将其再次绑定到其他对象。

    我错过了什么?

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

    2 回复  |  直到 12 年前
        1
  •  3
  •   Matt Hamilton    15 年前

    你想把 Text 属性返回到 TheText 它所在的用户控件的属性,对吗?所以你需要告诉我们财产的所在地。有几种方法可以做到这一点(使用findancestor可以使用relativesource),但最简单的方法是在XAML中为用户控件指定一个“名称”,并使用元素绑定进行绑定:

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

    现在,您的文本框将反映您已分配(或绑定)到“someControl.TheText”属性的值-您不需要更改任何其他代码,尽管您可能希望在基础myClass对象上实现inotifyPropertyChanged,以便绑定知道属性何时更改。

        2
  •  1
  •   Drew Noakes    15 年前

    马特为你的问题提供了解决方案。这里有更多的解释和提示,以阻止这个问题在未来。

    AS SomeControl.DataContext 设置在 SomeControl 构造函数,窗口的绑定 TheText="{Binding Path=MyStringProp}" 有一个 Source 类型的 恒流控制 不是 MyClass 如你所愿。

    任何在运行时失败的绑定都会导致调试消息被记录到Visual Studio的输出面板中。在这种情况下,您可能会看到“somecontrol”类型的对象上不存在这样的属性“myStringProp”,这应该会引起您的怀疑。

    我认为每个人都会发现WPF数据绑定需要一些时间来学习,特别是调试,但是要坚持下去。WPF中的数据绑定真的非常棒,我仍然很高兴知道它使我的UI上的数据保持最新。