【问题标题】:Two way binding - Control to Item in List - in WPF?两种方式绑定 - 控件到列表中的项目 - 在 WPF 中?
【发布时间】:2013-10-20 19:02:33
【问题描述】:

项目结构(伪代码):

Backend:

Controler // controler class
  List<Item> ItemsList
    Item // Model/Data 'struct' kind of class
      decimal Centimeters
      decimal Inches

  int ItemIndex // index of item in ComboBox selected for work

UI:

MainWindow
  // TextBoxes
  Centimeters
  Inches

  ComboBox ItemIndex

功能: 当我在 ComboBox 中选择 ItemIndex 时,Item 中的属性 (Inches,..) 以及 List 中的相应索引应该以某种方式将双向绑定到 TextBoxes。 用户可以使用文本框或控制器更改项目中的数据,控制器根据用户输入的值计算剩余值。

有没有一些简单的方法可以在 WPF 中进行绑定?

我刚开始使用 WPF,所以如果问题有点模糊或非常基本,我深表歉意。 我觉得有一个巧妙的解决方案,但我有点卡在这里。

我知道我可以通过 PropetyChanged 事件的可怕手工路由来解决这个问题。从文本框到窗口到​​控制器到将分配给属性的项目。和同样的方式回来。 我在应用程序的 Winforms 版本中实现了这样的功能,但看起来很混乱。 仍然希望有更优雅的解决方案。你能帮忙吗?

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    这是您可以将TextBoxes 绑定到SelectedItemComboBox 的方法。这里我假设你的ComboBoxItemsSourceList&lt;Item&gt; 类型的

        <TextBox x:Name="Inches" Text="{Binding SelectedItem.Inches, ElementName=MyCombo}"/>
        <TextBox x:Name="Centis" Text="{Binding SelectedItem.Centimeters, ElementName=MyCombo}"/>
        <ComboBox x:Name="MyCombo"/>
    

    但在这种情况下,您的 Item 类应该实现 INotifyPropertyChanged 并从其设置器中为其属性 Centimeters 和 Inches 提高 PropertyChanged,如下所示

    public class Item : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(string name)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
    
            decimal centimeters;
            decimal inches;
    
            public decimal Centimeters
            {
                get { return centimeters; }
                set
                {
                    centimeters = value;
                    NotifyPropertyChanged("Centimeters");
                }
            }
    
            public decimal Inches
            {
                get { return inches; }
                set
                {
                    inches = value;
                    NotifyPropertyChanged("Inches");
                }
            }
    
        }
    

    【讨论】:

    • 所以如果我为 Item 对象中的属性实现 PropertyChanged,它会像这样动态绑定双向?
    • @nit:不知道默认模式是 2way。谢谢 !!你的答案很完美。
    • 很难相信它在 WPF 中如此简单 :) 非常感谢!
    • 这就是它的美妙之处:)
    • @Sangram - 我相信所有可编辑控件都将 TwoWay 作为默认模式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2017-01-03
    • 1970-01-01
    • 2017-07-30
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多