Lei Yang
Lei Yang

Reputation: 4325

Just curious: why WPF binding to control's properties not work?

I'm familiar with WPF binding and MVVM. One day when answering questions on Baidu Zhidao I encountered such case:

<Grid>
    <ListBox Name="lb" DisplayMemberPath="S"/>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.lb.ItemsSource = new ObservableCollection<Item>()
        {
            new Item("aa"),
            new Item("bb"),
            new Item("cc"),
        };
    }
}

public class Item : ListBoxItem //
{
    public Item(string s)
    {
        this.S = s;
    }
    public string S { get; set; }
}

If Item inherits ListBoxItem or other control, then nothing displays. But why? Isn't S always a property of an object?

Upvotes: 0

Views: 43

Answers (1)

Mark Feldman
Mark Feldman

Reputation: 16119

When you bind ItemsSource to data it creates a ListBoxItem for each element and displays it using the DisplayMemberPath you've specified. However if you bind to an array of ListBoxItem that you've created yourself in code-behind then it will use those instead. In the code you posted your Item class inherits ListBoxItem so it's a GUI element, not data. This is poor practice, but if it's what you actually intend to do then you don't need the S property, just set Content directly:

public class Item : ListBoxItem
{
    public Item(string s)
    {
        this.Content = s;
    }
}

But if you want to do it properly (e.g. MVVM) then don't inherit ListBoxItem and don't manipulate the UI elements directly in code-behind:

public class Item
{
    public Item(string s)
    {
        this.S = s;
    }
    public string S { get; set; }
}

Upvotes: 3

Related Questions