1

我知道这已经被多次询问不同的方式,但我就是不明白。为什么我在列表框中看不到我的测试字符串?

。CS

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

    public Window1()
    {
        InitializeComponent();

        myList.Add("test1");
        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>
4

2 回答 2

4

因为您的“myList”是一个字段。WPF 绑定仅适用于属性。将列表的声明更改为:

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

public ObservableCollection<string> myList { get { return _myList; } }
于 2009-11-02T08:20:16.833 回答
1

试试这种方式:

public Window1()
{
    InitializeComponent();

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

    this.DataContext = myList;
}

然后在 XAML 中:

<ListBox Name="MyListBox" ItemsSource="{Binding}"/>
于 2009-11-02T08:20:49.463 回答