【发布时间】:2015-04-08 08:54:03
【问题描述】:
我正在尝试获取使用 ListBox 所需的数据绑定。
我已将文本文件中的一些数据解析为ObservableCollection<ViewModel>,但列表框中的数据没有更新。
这里有一些信息:
解析器写入的数据:
class MainData
{
private static ObservableCollection<GroupViewModel> groupModelList = new ObservableCollection<GroupViewModel>();
public static ObservableCollection<GroupViewModel> GroupModelList
{
get { return groupModelList; }
}
}
GroupViewModel 拥有什么(不是所有内容,但都一样):
class GroupViewModel : INotifyPropertyChanged
{
private GroupModel groupModel;
public event PropertyChangedEventHandler PropertyChanged;
public GroupViewModel()
{
groupModel = new GroupModel();
}
public string Name
{
get { return groupModel.name; }
set
{
if (groupModel.name != value)
{
groupModel.name = value;
InvokePropertyChanged("Name");
}
}
}
...
}
GroupModel 持有什么:
class GroupModel
{
public string name { get; set; }
}
这是解析器向GroupModelView 添加新项目的方式:
if (split[0] == "group")
{
currentGroup = new GroupViewModel();
currentGroup.Name = split[1];
MainData.GroupModelList.Add(currentGroup);
}
我使用这些 XAML 选项在我的 WPF 应用程序中创建了一个 ListBox:
<Window x:Class="SoundManager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:SoundManager.ViewModels"
xmlns:vm2="clr-namespace:SoundManager.Code"
Title="MainWindow" Height="720" Width="1280">
<Window.Resources>
<vm:MainViewModel x:Key="MainViewModel" />
<vm2:MainData x:Key="MainData" />
</Window.Resources>
<ListBox Grid.Row="2" Height="484" HorizontalAlignment="Left" Margin="12,0,0,0" Name="lbFoundItems" VerticalAlignment="Top" Width="201" ItemsSource="{Binding Source={StaticResource MainData}, Path=GroupModelList/Name}" />
但由于某种原因,数据未在 UI 中更新(新项目未在 UI 中明显添加)。
我刚刚开始使用 MVVM 模式和数据绑定,但我不知道我做错了什么。
提前致谢!
【问题讨论】: