ObservableCollection->列表框
我知道这个问题已经被多次以不同的方式询问过,但我就是不明白。为什么我在列表框中看不到我的测试字符串?
.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>
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("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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你的“myList”是一个字段。 WPF 绑定仅适用于属性。将列表的声明更改为:
Because your "myList" is a field. WPF binding only works with properties. Change your list's declaration to:
尝试这样:
然后在 XAML 中:
Try it this way:
and then in XAML: