开发者

WPF, ObservableCollection and listbox

I have following code

private static ObservableCollection<myColor> myItems = new ObservableCollection<myColor>();
myItems.Add(new myColor("red"));

When object myColor is this class

public class myColor
{
    public string color { get; set; }
    public myColor(string col)
    {
        this.color = col;
    }
}

Trouble is when I try to show item in listbox

<ListBox Margin=开发者_运维百科"12,52,12,12" Name="listBox1" ItemsSource="{Binding}" />

It only shows "myColor" object instead of "color" variable. How can I show variable from this object?


If you only want to display a string property of the item use DisplayMemberPath on the ListBox.

Otherwise use ItemTemplate, which you can set to a DataTemplate that defines how each of your items looks like and can be of any complexity (i.e. can include other controls).


First set the DataContext for the window, as shown below :

        public Window1()
        {
            InitializeComponent();

            myItems.Add(new myColor("red"));
            myItems.Add(new myColor("green"));

            //Set the DataContext for the window
            this.DataContext = myItems;
        }

Now change the XAML to:

<ListBox Margin="12,52,12,12" Name="listBox1" ItemsSource="{Binding}" DisplayMemberPath="color" />

That's all. It should solve your problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜