Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Expander IsExpanded binding

I have an Expander control with its 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>
like image 728
netraju Avatar asked Feb 01 '10 20:02

netraju


3 Answers

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
like image 145
user7116 Avatar answered Nov 11 '22 00:11

user7116


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>
like image 6
imekon Avatar answered Nov 11 '22 00:11

imekon


With Silverlight I do this:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

<Expander Name="pExpander" IsExpanded="True" Header="Preview">
    <i:Interaction.Triggers>
        <ei:PropertyChangedTrigger Binding="{Binding ShowPreview, Mode=OneWay}">
            <ei:ChangePropertyAction PropertyName="IsExpanded" Value="{Binding ShowPreview, Mode=OneWay}"/>
        </ei:PropertyChangedTrigger>
    </i:Interaction.Triggers>
    <TextBlock Text="{Binding Path=Message, Mode=OneWay}"></TextBlock>    
</Expander>
<Expander Name="pExpander1" IsExpanded="True" Header="Preview 1">
    <i:Interaction.Triggers>
        <ei:PropertyChangedTrigger Binding="{Binding ShowPreview, Mode=OneWay}">
            <ei:ChangePropertyAction PropertyName="IsExpanded" Value="{Binding ShowPreview, Mode=OneWay}"/>
        </ei:PropertyChangedTrigger>
    </i:Interaction.Triggers>
    <TextBlock Text="{Binding Path=Message1, Mode=OneWay}"></TextBlock>    
</Expander>
//...

The binding is not lost when you manualy expand/collapse one Expander...

like image 1
Tonio Avatar answered Nov 11 '22 00:11

Tonio