c# - 当代码在运行时更新时,将 Observable 集合绑定到组合框有效。但是在再次构建解决方案后它不起作用
问题描述
我正在尝试将 an 绑定ÒbservableCollection
到ComboBox
using MVVM
。
这是模型:
public class ItemModel
{
public string Name{ get; set; }
}
视图模型:
public class ItemsViewModel : INotifyPropertyChanged
{
public ObservableCollection<ItemModel> ObsItems{ get; set; }
public ItemsViewModel ()
{
List<string> items=MyDataTable.AsEnumerable().Select(row => row.Field<string>
("Id")).Distinct().ToList();
ObsItems= new ObservableCollection<ItemModel>();
foreach (var item in items)
{
ObsItems.Add(
new ItemModel
{
Name = item
}
);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
看法:
<ComboBox HorizontalAlignment="Left" Margin="65,85,0,0" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding ObsItems}">
<ComboBox.DataContext>
<Models:ItemsViewModel />
</ComboBox.DataContext>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
从头开始构建时,此代码不起作用。但它在运行时工作,当视图代码 (xaml) 被修改时。一旦程序退出并再次运行,它就会停止工作。我错过了什么?
解决方案
您应该使用只读的 ObservableCollection 属性:
public class ItemsViewModel
{
public ObservableCollection<ItemModel> Items { get; }
= new ObservableCollection<ItemModel>();
public void InitializeItems()
{
Items.Clear();
foreach (var item in MyDataTable
.AsEnumerable()
.Select(row => row.Field<string>("Id"))
.Distinct()
.Select(name => new ItemModel { Name = name }))
{
Items.Add(item);
}
}
}
推荐阅读
- javascript - 如何重新计算相对坐标?
- javascript - getState() 在 React native 中有时会返回 idToken 而不是 localId 作为 userID
- android - 我们如何在 Chromecast Styled Media Receiver 中实现音频传递
- typescript - 打字稿:如何让第二个参数类型依赖于第一个参数值
- node.js - React 应用程序在运行时的环境变量
- python - 如何获取数据框列中的项目数?
- r - 结合dtplyr和multidplyr处理大型mutate操作
- apache-spark - 黄土火花/Pyspark
- node.js - 如何使用 websockets 创建代理
- google-bigquery - 查询以将文本附加到(不同的)字符串数组(更好的解决方案)到单个分号分隔的字符串