It can't seem to get WPF DataBinding in my head

Well, I'm not new to programming or C # per se, I just can't get WPF binding right in my head. My colleagues are raving about this (and yes, I will ask them too), but now I'm at a standstill.

Here is what I would like to do for starters:

As an example, I have a list of things like this:

List<Thing> thingList = Source.getList();

Now i used to go

foreach(Thing t in thingList)
{
    //add thing to combobox
}

But from what I can collect, is that I can somehow not do this, but use data binding to populate the combo box for me.

What I cannot get is where can I put a "thingList"? Am I doing it somewhere separately? Where can I place this property?

, , , - , .

, , , , ?

+5
3

ObservableCollection<T> WPF. - .

public class NameList : ObservableCollection<PersonName>
{
    public NameList() : base()
    {
        Add(new PersonName("A", "E"));
        Add(new PersonName("B", "F"));
        Add(new PersonName("C", "G"));
        Add(new PersonName("D", "H"));
    }
  }

  public class PersonName
  {
      private string firstName;
      private string lastName;

      public PersonName(string first, string last)
      {
          this.firstName = first;
          this.lastName = last;
      }

      public string FirstName
      {
          get { return firstName; }
          set { firstName = value; }
      }

      public string LastName
      {
          get { return lastName; }
          set { lastName = value; }
      }
  }

XAML.

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

  xmlns:c="clr-namespace:SDKSample"

  x:Class="Sample.Window1"
  Width="400"
  Height="280"
  Title="MultiBinding Sample">

  <Window.Resources>
    <c:NameList x:Key="NameListData"/>
  </Window.Resources>


<ListBox Width="200"
         ItemsSource="{Binding Source={StaticResource NameListData}}"  // Name list data is declared in resource
         ItemTemplate="{StaticResource NameItemTemplate}"
         IsSynchronizedWithCurrentItem="True"/>

xmnls:c . c, d, e x, ,

+2

, , , , .

: alernative - ComboBox, , ItemsSource.

XAML, , XAML, :

comboBox.ItemsSource = thingList;

, , ToString, , , . , :

, (, , ..), , DisplayMemberPath, , ( ).

, , INotifyCollectionChanged, ObersableCollection<T>.

+2

WPF Databinding combobox, .

, .

, , (BTW, , , ).

List<Thing> thingList = Source.getList();

foreach(Thing t in thingList)
{
   combobox.Items.Add( t );
}
+1
source

All Articles