As an analogy, we've got two Mr Men in a ComboBox:
Mr Happy Mr Grumpy
I've a property on my ViewModel (using MVVM to an extent, with a SelectionChanged event in the code behind) which I've called IsGrumpy which defaults to false if the Mr Man is happy and true if the Mr Man is grumpy. Obviously!
Now, Mr Happy might have had a heavy night in which case the user can set IsGrumpy (a CheckBox) to true and the value is persisted to Xml.
When the application reloa开发者_运维百科ds, the IsGrumpy property is set correctly, but when the view loads (and Mr Happy is loaded from persistence), SelectionChanged is fired and Mr Happy is no longer grumpy!
Are they any patterns or tricks (without using flag hacks) that can help me in my quest to keep Mr Happy grumpy!?
I'm not entirely sure as to why your using a SelectionChanged event here. You only need to work with the combobox selected item property change and this is easily done with binding.
Here's my rough thinking I hope that it helps. (Note that I've just typed it in without recourse to VS).
In your ViewModel all you need are the following:
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;}
}
Then in your view
<ComboBox x:Name="mrmenName" ItemsSource="{Binding MrMen}" SelectedItem="{Binding MrManSelected}"/>
That copes with the changing of the selection from MrHappy to MrGrumpy.
You would then have a dataModel for your
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;}
}
You obviously already have your MrMan classes instantiated and initialized with data from some data repository anyway.
Thinking about it you may want to override the setting of the IsGrumpy property within the MrMan data model rather than within the ViewModel but that's up to you.
精彩评论