【发布时间】:2018-04-14 15:25:38
【问题描述】:
我正在尝试根据结构构建一个使用模型-视图-视图模型设计模式的简单 C#/WinFoms 项目:
两个 UserControl 和关联的 ViewModel 之间的数据绑定不能正常工作。
MainForm 包含两个用户控件 (UC):Uc_Create、Uc_Iteration。
每个 UC 都包含一个与 ViewModel_xxx 中的关联属性相连的组合框,即
Uc_Create有:
this.comboBox1ComplexCreate.DataSource = oVM_Create.VM_Create_ListOfStringsInModel;
Uc_Iteration 有:
this.comboBox1ComplexIteration.DataSource = oVM_Iteration.VM_Iteration_ListOfStringsInModel;
问题:
当我将元素添加到 VM_Iteration_ListOfStringsInModel 时,相应 UC (comboBox1ComplexCreate) 中的组合框和模型中的列表已正确更改但另一个组合框 ( comboBox1ComplexIteration) 在Uc_Iteration 不是!
为什么????
如果我将模型中的List 更改为BindingList,一切正常。我做错了什么?
提前致谢!
型号:
namespace Small_MVVM
{
public class Model
{
private static readonly object m_oLock = new object();
private static Model instance;
public List<string> simplelistOfStrings;
private Model()
{
simplelistOfStrings = new List<string>();
}
public static Model GetInstance()
{
if (instance == null)
{
lock (m_oLock)
{
if (instance == null)
{
instance = new Model();
}
}
}
return instance;
}
}
}
ModelView_Create:
namespace Small_MVVM
{
class ViewModel_Create : NotifyPropertyChangedBase
{
private static Model oModel = Model.GetInstance();
private BindingList<string> _VM_Create_ListOfStringsInModel = new BindingList<string>(oModel.simplelistOfStrings);
public BindingList<string> VM_Create_ListOfStringsInModel
{
get
{
return _VM_Create_ListOfStringsInModel;
}
set
{
_VM_Create_ListOfStringsInModel = value;
this.FirePropertyChanged(nameof(VM_Create_ListOfStringsInModel));
}
}
}
}
ModelView_Iteration:
namespace Small_MVVM
{
class ViewModel_Iteration : NotifyPropertyChangedBase
{
private static Model oModel = Model.GetInstance();
public ViewModel_Iteration()
{
}
BindingList<string> _VM_Iteration_ListOfStringsInModel = new BindingList<string>(oModel.simplelistOfStrings);
public BindingList<string> VM_Iteration_ListOfStringsInModel
{
get
{
return _VM_Iteration_ListOfStringsInModel;
}
set
{
_VM_Iteration_ListOfStringsInModel = value;
this.FirePropertyChanged(nameof(VM_Iteration_ListOfStringsInModel));
}
}
}
}
这是实现INotifyPropertyChange接口的抽象类NotifyPropertyChangedBase:
public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool CheckPropertyChanged<T>(string propertyName, ref T oldValue, ref T newValue)
{
if (oldValue == null && newValue == null)
{
return false;
}
if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue))
{
oldValue = newValue;
return true;
}
return false;
}
private delegate void PropertyChangedCallback(string propertyName);
protected void FirePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
【问题讨论】:
-
尝试将数据源绑定到viewmodel属性
this.comboBox1ComplexCreate.Bindings.Add("DataSource", oVM_Create, "VM_Create_ListOfStringsInModel", true) -
感谢法比奥!不幸的是它仍然不起作用:(
-
你试过 observablecollection 吗?
标签: c# winforms design-patterns mvvm