簡體   English   中英

WPF中的兩種方式綁定-控件到列表中的項目?

[英]Two way binding - Control to Item in List - in WPF?

項目結構(偽代碼):

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中具有列表中相應索引的屬性(英寸,..)應該以某種方式綁定到文本框的雙向。 用戶可以使用文本框或控制器根據用戶輸入的值計算剩余值來更改項目中的數據。

有一些簡單的方法可以在WPF中進行綁定嗎?

我只是從WPF開始,所以如果問題有點模糊或非常基本,我會深表歉意。 我覺得有一個很好的解決方案,但是我在這里有些卡住。

我知道我可以通過可怕的PropetyChanged事件路由解決此問題。 從文本框到窗口再到控制器再到將分配給屬性的項目。 同樣的方式。 我已經在應用程序的Winforms版本中實現了這樣的實現,但是看起來很混亂。 仍然希望有更優雅的解決方案。 你能幫我嗎?

這是將TextBoxes綁定到ComboBox SelectedItem的方法。 在這里,我假設您的ComboBoxItemsSource類型為List<Item>

    <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");
            }
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM