[英]wpf binding listbox items to a static list
I really looked hard.我真的很难看。 There seems to be something I am missing.
似乎有什么我想念的。 Using .net 4.5.
使用 .net 4.5。
Here's my XAML:这是我的 XAML:
<Window x:Class="a.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:a"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="201" Margin="144,33,0,0" VerticalAlignment="Top" Width="115" ItemsSource="{Binding (local:myClass.myStaticList)}"/>
<Button Content="Button" HorizontalAlignment="Left" Height="48" Margin="282,247,0,0" VerticalAlignment="Top" Width="150" Click="Button_Click"/>
</Grid>
</Window>
and here's the code behind:这是背后的代码:
using System.Collections.ObjectModel;
using System.Windows;
namespace a
{
public class myClass
{
public static ObservableCollection<string> myStaticList { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myListBox.Items.Add("aaa");
myListBox.Items.Add("bbb");
myListBox.Items.Add("ccc");
myListBox.Items.Add("ddd");
myListBox.Items.Add("eee");
myListBox.Items.Add("rrr");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
<--- Breakpoint here
}
}
}
Real simple.真简单。 The button is used only to pause the running with a breakpoint and see whether the data was introduced from
myListBox
to myControl.myList
.该按钮仅用于通过断点暂停运行并查看数据是否从
myControl.myList
引入到myListBox
。
It doesn't.它没有。
myList
remains null. myList
保持为空。 What am I missing?我错过了什么?
Help please!请帮忙! TIA
TIA
You have to create an instance and add data to your ObservableCollection
, not to the ListBox
that is binding to it.您必须创建一个实例并将数据添加到
ObservableCollection
,而不是添加到绑定到它的ListBox
中。
MainWindow.cs :主窗口.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myClass.myStaticList = new ObservableCollection<string>();
myClass.myStaticList.Add("aaa");
myClass.myStaticList.Add("bbb");
myClass.myStaticList.Add("ccc");
myClass.myStaticList.Add("ddd");
myClass.myStaticList.Add("eee");
myClass.myStaticList.Add("fff");
}
}
XAML : XAML:
<Grid>
<ListBox x:Name="ListBox1" Margin="0" ItemsSource="{Binding myStaticList}">
<ListBox.DataContext>
<local:myClass/>
</ListBox.DataContext>
</ListBox>
</Grid>
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.