开发者

ObservableCollection -> Listbox

I know this has been asked different ways several times, but I'm just not getting it. Why don't I see my test strings in the listbox?

.cs

 public partial class Window1 : Window
 {
    public ObservableCollection<string> myList = new ObservableCollection<string>();

    public Window1()
    {
        InitializeComponent();

        myList.Add("test开发者_开发知识库1");
        myList.Add("test2");
    }
}

.xaml

<Window x:Class="WpfApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    x:Name="thisWindow">
    <Grid>
        <ListBox Name="MyListBox" ItemsSource="{Binding myList, ElementName=thisWindow}"/>
    </Grid>
</Window>


Because your "myList" is a field. WPF binding only works with properties. Change your list's declaration to:

private ObservableCollection<string> _myList = new ObservableCollection<string>();

public ObservableCollection<string> myList { get { return _myList; } }


Try it this way:

public Window1()
{
    InitializeComponent();

    myList.Add("test1");
    myList.Add("test2");

    this.DataContext = myList;
}

and then in XAML:

<ListBox Name="MyListBox" ItemsSource="{Binding}"/>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜