添加到视图模型的属性不会向组合框生成项
本文关键字:组合 视图 模型 属性 添加 | 更新日期: 2023-09-27 18:37:26
我的视图模型类非常简单。
class Presenter
{
public IEnumerable<String> JustFake => new List<String> { "aaa", "bbb" };
public Presenter() { }
}
在 XAML 中,我添加了一个绑定到属性的组合框,如下所示。
<Window.DataContext>
<local:Presenter/>
</Window.DataContext>
...
<ComboBox x:Name="comboBox"
ItemsSource="{Binding JustFake}"/>
但是,尽管智能感知找到了 JustFake,但这些值并未显示在组合框中。它是空的。我尝试过实现INotify...等,但没有任何区别。我真的说不出我能错过什么。我应该继承其他东西吗(我看到一个博客,他们提到了 BindableBase,无论那个类是什么)?我应该以另一种方式介绍演示者吗?
public IEnumerable<String> JustFake = new List<String> { "aaa", "bbb" };
声明一个公共字段,该字段不能被约束。您需要一个属性:
public IEnumerable<String> JustFake { get; set;}
public Presenter()
{
JustFake = new List<String> { "aaa", "bbb" };
}
如果要在构造函数之后设置属性,则需要使用 INotifyPropertyChanged
,如果要修改集合,请确保使用 ObservableCollection
而不是 List
,因为它实现INotifyCollectionChanged
。
更新:您显然使用的是 C# 6 表达式成员,因此您可能在这方面没问题。
更新 2:从您报告的异常来看,您的DataContext
似乎未设置,或者稍后设置为this
。检查并确保没有任何东西覆盖它。
绑定到ItemsControl
上的ItemSource
,例如ListBox
或DataGrid
需要公共属性:
class Presenter
{
public List<string> JustFake { get; set; }
public Presenter()
{
JustFake = new List<string> { "aaa", "bbb" };
}
}
若要支持返回到 UI 的通知,集合需要INotifyPropertyChanged
实现,通常更容易使用或从已实现它的集合类派生。ObservableCollection<T>
:
class Presenter
{
public ObservableCollection<string> JustFake { get; set; }
public Presenter()
{
JustFake = new ObservableCollection<string> { "aaa", "bbb" };
}
}