开发者

What is wrong with this simple binding?

开发者 https://www.devze.com 2023-01-10 17:02 出处:网络
I\'m trying to bind a list box in the simplest manner possible with the goal of understanding binding a little better.All examples I see online show data template, and I don\'t want to get that compli

I'm trying to bind a list box in the simplest manner possible with the goal of understanding binding a little better. All examples I see online show data template, and I don't want to get that complicated yet. I have a collection of objects. These objects have a property of string type, and that's what I want to show in the list box. Below is all the code. Nothing shows up when I run this. What am I missing?

// The simple object
public class GameData 
{
  public string Team { get; set; }
}

// Window1.xaml
<Grid>
  <ListBox ItemSource="{Binding GameCollection}" DisplayMemberPath="Team"></ListBox>
</Grid>

// Window1.xaml.cs file
public partial class Wind开发者_如何学Pythonow1 : Window
{
  //public ObservableCollection<GameData> GameCollection;
  // Changed to property per SLaks idea but still no luck
  public ObservableCollection<GameData> GameCollection
  {
    get;
    set;
  }


  public Window1()
  {
    GameCollection = new ObservableCollection<GameData>();
    GameCollection.Add("Tigers");
    GameCollection.Add("Indians");
    GameCollection.Add("Royals");

    InitializeComponent();
  }
}


Remove your GameCollection field and set the Window's DataContext instead.

You can then bind directly to the DataContext using {Binding}.


Here's some changes I made to get it to work:

// The simple object
public class GameData
{
    public string Team { get; set; }
}

public partial class Window1 : Window
{
    public ObservableCollection<GameData> GameCollection { get; set; }

    public Window1()
    {
        this.DataContext = this;
        GameCollection = new ObservableCollection<GameData>();
        GameCollection.Add(new GameData(){Team = "Tigers"});
        GameCollection.Add(new GameData(){Team = "Royals" });
        GameCollection.Add(new GameData(){Team = "Indians" });

        InitializeComponent();
    }
}


<Grid>
    <ListBox ItemsSource="{Binding GameCollection}" DisplayMemberPath="Team"/>
</Grid>
0

精彩评论

暂无评论...
验证码 换一张
取 消