简体   繁体   中英

Two way binding - Control to Item in List - in WPF?

Structure of project (pseudo code):

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

Functionality: When I select ItemIndex in ComboBox, properties (Inches,..) in Item with respective index in List should somehow bind two-way to the TextBoxes. Data in the Items can be changed by user using TextBoxes or by Controller that computes the remaining value based on what which values user entered.

Is there some simple way to do the binding in WPF ?

I'm just starting with WPF so I do apologize if the problem is somehow vague or very basic. I have a feeling there is a slick solution, but I got a bit stuck here.

I know I can solve this with a horrible handmade routing of PropetyChanged event. From Textbox to Window to Controller to Item which will assign to Property. And same way back. I have it implemented like this in Winforms version of the app but it looks quite chaotic. Still hoping for more elegant solution. Can you help?

This is how you can bind TextBoxes to SelectedItem of ComboBox . Here I am assuming the ItemsSource of your ComboBox is of type 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"/>

But in this case, your Item class should implement INotifyPropertyChanged and raise PropertyChanged for its properties Centimeters and Inches from their setters like below

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM