tags:

views:

460

answers:

3

I have an expander control with it's IsExpanded property bound to a bool in the mvvm model. The binding works fine until you dont touch the expander. Once you click the arrow in the expander to expand, the binding stops working. Setting the bool ShowPreview to false in the model doesn't collapse the expander.

 <Expander Name="pExpander" 
IsExpanded="{Binding Path=ShowPreview,Mode=OneWay}"
Header="Preview">             
    <TextBlock Text="{Binding Path=Message, Mode=OneWay}"></TextBlock>    
</Expander>
+4  A: 

If you remove Mode=OneWay does that fix the problem?

Upon reading your other CTQ (changes to the GUI do not affect the model), I don't have a good suggestion for how to limit the change being seen by the underlying data. What is the difference in:

myModel.MyProperty = true; // in *your* code behind

And

myModel.MyProperty = true; // done by a binding
sixlettervariables
yes removing mode=oneway works.
netraju
A: 

Do three things,

Make sure your ViewModel is implementing INotifyPropertyChanged. Your ui wont know about the change if your view model doesnt inform it when the property changes

Change the Mode to TwoWay, you want your view model updated when the expander changes and you want your expander updated when the view model changes

Lastly if the above two don't work use a debug converter to ascertain if your binding is failing. there is an example here of how to do this. This is a technique every wpf developer needs.

I know there was an issue with radio buttons that they would lose their bindings when another button in the group was set, i don't think that is the issue here, however a debug converter will help you figure this out.

Aran Mulholland
Thanks for the replies. Yes the Model does implement INotifyPropertyChanged. The binding works fine as long as you don't touch the expander. As soon as you mouse click on the expander to expand, the binding doesn't work anymore. In debug you can see that IsExpanded is getting set to either true or false. But visually the expander stays expanded.
netraju
if you put the debug converter on, does the debug converter keep getting hit every time you change the collapsed state?
Aran Mulholland
A: 

What caught me out here is that IsExpanded is OneWay by default, so

<Style TargetType="TreeViewItem">
    <Setter Property="IsExpanded" Value="{Binding Expanded}"/>
</Style>

doesn't work the way I expected. Only if you add Mode=TwoWay, then it works (i.e. the item starts paying attention to my Expanded property, and updating it), as in

<Style TargetType="TreeViewItem">
    <Setter Property="IsExpanded" Value="{Binding Expanded, Mode=TwoWay}"/>
</Style>
imekon