【发布时间】:2017-01-12 16:44:56
【问题描述】:
我正在创建一个 N 层 wpf mvvm 项目。我想从数据库中获取要显示在列表框中的项目列表。我想将列表框绑定到 ViewModel (VM) 中的属性。问题是绑定对我不起作用,列表框总是空的。 当我在“返回标签”上放置断点时,它会在显示表单之前完全填充。
MainWindow() 构造函数中的DataContext = App.ViewModel;。
在我的 XAML 中
<ListBox ItemsSource="{Binding Tags, Mode=OneWay}" Height="161" HorizontalAlignment="Left" Margin="236,6,0,0" Name="lstTags" VerticalAlignment="Top" Width="130" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Tags.Name}" />
<TextBlock Text="{Binding Tags.Description}" />
<!--<CheckBox IsChecked="{Binding Deleted, Mode=TwoWay}"/>-->
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在我的虚拟机中:当我在“返回标签”上设置断点时,它已完全填充。
private TagCol _tags;
public TagCol Tags
{
get {
TagColData tcd = new TagColData();
_tags = tcd.LoadAll();
//NotifyPropertyChanged("Tags");
return _tags;
}
set {
_tags = value;
NotifyPropertyChanged("Tags");
}
}
TagCol:
公共类 TagCol { 私有 ObservableCollection _tagCol = new ObservableCollection();
/// <summary>Collection (list) of Tag objects</summary>
public ObservableCollection<Tag> Collection {
get { return _tagCol; }
set
{
_tagCol = value;
}
}
public TagCol()
{
}
}
【问题讨论】:
-
您是否将 MainWindow(或 ListBox 的任何父控件)的 DataContext 设置为您的视图模型类的实例?
-
能否包含
TagCol的定义 -
使用 Snoop 在运行时检查绑定和控件。 TagCol 必须实现 IEnumerable 才能工作。
-
大家好。我已经用 TagCol 类更新了这个问题。 Clemens DataContext 是在 MainWindow() 构造函数中设置的。
-
Snoop 很有趣,虽然有点吓人,它会像这样扰乱您的应用程序。谢谢。