views:

33

answers:

2

Hi All,

I am using MVVM architecture to develop a WPF application...

So far everything has been going fine.

I have run into an issue with binding visiblity. I want to minimize writing code in the code behind if i can but if it's REQUIRED then I dont mind doing it.

I have a ViewModel. THis model exposes a boolean and 2 commands. A connect command, a disconnect command, and a DeviceCurrentlyConnected Bool.

Basically I have decided to make 2 buttons but have the button visiblity based on the boolean.

So i have had a hard time with this. I tried styles with triggers for a long time.

<Button Visibility="Hidden" Content="{x:Static UIStrings:ClientStrings.DeviceBar_DisconnectCommandName}" VerticalAlignment="Center" HorizontalAlignment="Center" Height="{Binding ElementName=this.Content, Path=DesiredHeight}" Margin="10" Name="Disconnect" Command="{Binding DisconnectCurrentDeviceCommand}">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding DataCotext.DeviceConnected, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" Value="True">
                    <Setter Property="Visibility" Value="Visible"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

I can not get styles to work at all.

Basically the functionality that I want is:

DeviceConnected = false: Display a button with content Connect and command bound to the ConnectCommand.

DeviceConnected = true: Display a button with content disconnect and command bound to the DisconnectCommand.

for a button to be displayed and bound to the connect device when no device is currently connect and for a button to be displayed when a device is connected that is bound to the disconnect command and to say the word disconnect.

+1  A: 

Write up a bool to visibility converter and then use the converter on your buttons. Five minute recipe for a decent BoolToVisibilityConverter is a good post to read up on creating/using a visibility converter.

What I've done in the past is use a bool to visibility converter and passed in the button's IsEnabled property as the parameter to the converter. Since the button is dis/enabled by the command in the model with the CanExecute method, you can then use the IsEnabled property to set the visibility of the button with the converter.

Metro Smurf
+1  A: 

The reason that your trigger doesn't work is that the style is overridden by the attribute on the button itself.

You can use a converter as Metro Smurf suggests, alternatively you can move the visibility attribute into the style so that the trigger works properly

Just add:

<Style.Setters>
    <Setter Property="Visibility" Value="Hidden" />
</Style.Setters>

To the style and then remove the attribute.

Ben Childs