作为类比,我们有两个在ComboBox中的Mr Men:
快乐先生,暴躁先生
我在我的ViewModel上有一个属性(在一定程度上使用了MVVM,在后面的代码中有一个SelectionChanged事件),我已经调用了IsGrumpy,如果男人是快乐的,如果男人是暴躁的,那么它的默认值为false。很明显!
现在,Happy先生可能已经经历了一个繁重的夜晚,在这种情况下,用户可以将IsGrumpy (a CheckBox)设置为true,并将该值持久化到Xml。
当应用程序重新加载时,IsGrumpy属性被正确设置,但是当视图加载(并且Mr Happy是从持久性加载的)时,SelectionChanged被触发,Mr Happy不再暴躁!
它们有没有什么模式或技巧(不使用旗帜黑客),可以帮助我保持快乐暴躁先生!?
发布于 2010-09-24 16:52:09
我不能完全确定为什么要在这里使用SelectionChanged事件。您只需要处理combobox selected item属性的更改,这很容易通过绑定完成。
这是我粗略的想法,我希望它能有所帮助。(请注意,我只是在没有求助于VS的情况下键入了它)。
在您的ViewModel中,您所需要的全部内容如下:
private MrMan fieldMrMan;/// best to ensure that this is instanciated.
private List<MrMan> fieldMrMen;/// best to ensure that this is instanciated.
public bool IsGrumpy
{
get{return this.fieldMrMan.IsGrumpy;}
set
{
if(this.fieldMrMan.Name!="MrGrumpy")
this.fieldMrMan.IsGrumpy=value;
}
public MrMan MrManSelected
{
get{return this.fieldMrMan;}
set
{
if(value == this.fieldMrMan)
return;
///Raise property change event here
}
}
public List<MrMan> MrMen
{
get{return fieldMrMen;}
}那么在你看来
<ComboBox x:Name="mrmenName" ItemsSource="{Binding MrMen}" SelectedItem="{Binding MrManSelected}"/>这解决了将选择从MrHappy更改为MrGrumpy的问题。
然后,您将拥有一个dataModel,用于
public class MrMan
{
public MrMan(string name, bool grumpy)
{
this.Name = name;
this.IsGrumpy = grumpy;
}
public string Name{get;set;}
public bool IsGrumpy{get;set;}
}显然,您已经实例化了MrMan类,并使用来自某个数据存储库的数据进行了初始化。
考虑到这一点,您可能希望在MrMan数据模型中覆盖IsGrumpy属性的设置,而不是在ViewModel中,但这取决于您。
https://stackoverflow.com/questions/3785262
复制相似问题