【问题标题】:Binding user control to object proporties with minimal effort以最小的努力将用户控件绑定到对象比例
【发布时间】:2013-02-05 10:40:32
【问题描述】:

我有用户控制权:

<UserControl>
    <TextBox Name="TB1"/>
    <TextBox Name="TB2"/>
</UserControl>

后面的代码:

public partial class MyControl : UserControl
{
  public TwoStrings TsObj { get; set; }
  public MyControl()
  {
      InitializeComponent();
  }
}

在哪里

public class TwoStrings
{
    string S1 { get; set; }
    string S2 { get; set; }
}

如何以最少的代码更改将 TsObj.S1 绑定到 TB1.Text 和 TsObj.S2 到 TB2.Text?不应更改 TwoStrings。对象的更新应该反映在控制上。请提供代码示例。

【问题讨论】:

    标签: c# wpf xaml binding user-controls


    【解决方案1】:

    互联网上有很多关于 wpf/silverlight 数据绑定的资源,甚至在 stackoverflow 中也是如此。但长话短说,您可以这样做:

    <UserControl>
      <TextBox Name="TB1" Text="{Binding S1}" />
      <TextBox Name="TB2" Text="{Binding S2}"/>
    </UserControl>
    
    public partial class MyControl : UserControl
    {
        public TwoStrings TsObj { get; set; }
        public MyControl()
        {
          InitializeComponent();
    
          this.DataContext = TsObj = new TwoStrings();
        }
    }
    

    编辑:请注意,如果您通过 TwoStrings 实例中的代码更改属性,这将不会反映在文本框中,因为您需要在 TwoStrings 中实现 INotifyPropertyChanged 接口(即ViewModel - MVVM 模式中的 VM)来获得两种方式的数据绑定。否则,您将只能通过一种方式将文本框中的数据绑定到 datacontext (TwoString) 上的属性

    【讨论】:

    • 谢谢。我能想到的所有其他方式都更复杂。 INotifyPropertyChanged 应该在哪里实现?
    猜你喜欢
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多