Niko_fhtw
Niko_fhtw

Reputation: 13

Conditional display of image in c#

I am currently trying to conditionaly display an image. I read quite a bit about valueConverters and triggers, but i strongly believe that there has to be an easier solution for this easy problem.

The XAML:

 <Image Source="C:\Users\Niko\Pictures\red.png" IsEnabled="{Binding IsOn}"></Image>

The code behind:

namespace MVVM {
public class Globals
{
    int i = 2;

    public bool IsOn
    {
        get
        {
            if (i == 1 )
                return true;
            else
                return false;
        }

    }
}

I played around with the integer i to see if the image gets displayed or not. Any advice is greatly apreciated!

Upvotes: 1

Views: 4449

Answers (2)

Arie
Arie

Reputation: 5373

If you don't want to put a Visibility property in your ViewModel and don't want to use converters, you can use a DataTrigger (here I don't have a ViewModel at all, the image is visible if the ToggleButton is checked):

<Image Source="C:\Users\Niko\Pictures\red.png">
        <Image.Style>
            <Style TargetType="{x:Type Image}">
                <Setter Property="Visibility"
                        Value="Visible" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsChecked, ElementName=tg}"
                                 Value="False">
                        <Setter Property="Visibility"
                                Value="Hidden" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>

    <ToggleButton Name="tg" Content="Show" HorizontalAlignment="Left" VerticalAlignment="Bottom" />

Upvotes: 4

Lithium
Lithium

Reputation: 393

Bind the Image's Visibility to IsOn and use the built in BooleanToVisibilityConverter.

<Image Source="C:\Users\Niko\Pictures\red.png" Visibility="{Binding Visibility, Converter={StaticResource BoolToVis}}"/>

Then add the BooleanToVisibilityConverter as a static resource in either the <Window.Resources> for just that window or <Application.Resources> for your whole application.

<BooleanToVisibilityConverter x:Key="BoolToVis"/>

Note that x:Key is the name that you use to reference the converter after StaticResource.

Upvotes: 7

Related Questions