Question

I've an WPF application where tried to implement MVVM pattern and Prism 2. I have a Usercontrol which has subscribed to an event fired from another Usercontrol. I would like to toggle visibility of few child elements in the subscribing control. Events are fired properly, even I am successfully able to bind data to some elements. How do I bind Visibility or any style property for that matter with the ViewModel and change them dynamically.

Was it helpful?

Solution

You can have a boolean property in your ViewModel and bind that property to the Visibility property of your controls. Since you will be asigning a boolean value and the Visibility property is expecting a Visibility enumeration value, you will have to use the BooleanToVisibilityConverter converter to make the conversion,

<Style.Resources>
     <BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
</Style.Resources>

<Image Visibility="{Binding Path=ShowImage, 
                    Converter={StaticResource booleanToVisibilityConverter}}"/>

Hope this helps.

Ezequiel Jadib

OTHER TIPS

Although adding a Boolean property and using a value converter works, I would recommend adding a property of type Visibility to your ViewModel, e.g.

public Visibility ImageVisibility
{
    get { return shouldShowImage ? Visibility.Visible : Visibility.Collapsed }
}

The advantage of this method is you don't need to write a converter for every property you want to express in a visual way (e.g. for a stock level that turns a label red when it drops below 10, you could have a converter you use once or just expose a StockLabelBrush property from your VM)

I know this is an old question, but there's a simple solution for people who run into this issue and find this answer.

In your view model, create a "Visibility" property like so:

public Visibility ShowModifyButtons
    {
        get { return (Visibility)GetValue(ShowModifyButtonsProperty); }
        set { SetValue(ShowModifyButtonsProperty, value); }
    }
public static readonly DependencyProperty ShowModifyButtonsProperty =
        DependencyProperty.Register("ShowModifyButtons", typeof(Visibility), typeof(FileMatchViewModel),
        new UIPropertyMetadata(Visibility.Collapsed));

In your XAML, bind to it like so:

 <Button Focusable="False" Content="Save" Width="100" Margin="10" Visibility="{Binding ShowModifyButtons}"/>

Now, from your view model, you can set ShowModifyButtons to Visibility.Collapsed or Visibility.Visible as needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top