我真的不明白为什么以及在后台发生了什么,所以请帮助我。我有一个简单的 ListView:
<ListView Height="100" HorizontalAlignment="Left" Margin="67,84,0,0" ItemsSource="
{Binding Path=ListBinding}" Name="listView1" VerticalAlignment="Top" Width="351" />
和一个按钮:
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="162,41,0,0"
Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
我将数据上下文设置为我的“viewmodel”类:
InitializeComponent();
this.DataContext = new VM1();
现在,如果我在 VM1 的构造函数中初始化 obscollection,则当我使用 button1_click 函数填充 ListBinding 时,绑定将起作用:
private void button1_Click(object sender, RoutedEventArgs e)
{
(this.DataContext as VM1).Do();
}
public VM1()
{
ListBinding = new ObservableCollection<string>();
}
public void Do()
{
ListBinding.Add("VM1 works 1");
ListBinding.Add("VM1 works 2");
}
但是如果我在 Do() 函数中初始化它,它不会:
public VM1()
{ }
public void Do()
{
ListBinding = new ObservableCollection<string>();
ListBinding.Add("VM1 NOT works 1");
ListBinding.Add("VM1 NOT works 2");
}
我想这个问题的答案可能是一个班轮,我想了解“为什么”。谢谢!