Val
Val

Reputation: 1822

Change a Path's Fill color depending on a bool property

I have a DataTemplate with a Path in a ResourceDictionary and I want to change the Fill color for the Path (would choose between two colors) depending on a bool property from the viewmodel.

<DataTemplate x:Key="FileIcon">
    <Path Data="M20.8573547,8.0085467..." Fill="#F0F1F3" Width="30" Height="30"/>
</DataTemplate>

I presume, I need to use some converter but not sure how to write the XAML code for it. Something like this?

<Path Fill="{Binding MyBoolProperty, RelativeSource={RelativeSource FindAncestor, AncestorType=Path}, Converter={StaticResource BoolToColorConverter}}"/>

Upvotes: 1

Views: 1426

Answers (2)

The Path isn't an ancestor of itself. If the viewmodel is the Path's DataContext, a conventional binding should suffice:

<Path 
    Fill="{Binding MyBoolProperty, Converter={StaticResource BoolToColorHiddenConverter}}"
    />

You could also skip the converter and use a Style trigger. Note that the default Fill is no longer set as an attribute in this version; if it is, then it'll override anything the Style does.

<Path
    Data="M20.8573547,8.0085467..." 
    Width="30" 
    Height="30"
    >
    <Path.Style>
        <Style TargetType="Path">
            <Setter Property="Fill" Value="#F0F1F3" />
            <Style.Triggers>
                <DataTrigger
                    Binding="{Binding MyBoolProperty}"
                    Value="True"
                    >
                    <Setter Property="Fill" Value="FluorescentBeige" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Path.Style>
</Path>

Upvotes: 3

Matt L.
Matt L.

Reputation: 768

If you want to use a converter, you can follow this example code for making one:

1. Make a new class

2. Use the following namespaces:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

3. Inherit and implement the IValueConverter Interface

4. In the Convert function, evaluate the value parameter and return the corresponding color you want

Example Code

class BoolToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((bool)value == true)
        {
            // return the color you want
        }
        else
        {
            // return the color you want
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Upvotes: -1

Related Questions