根据bool属性更改路径的填充颜色

时间:2017-08-23 15:36:24

标签: wpf xaml

我在ResourceDictionary中有一个DataTemplate Path,我想更改Fill的{​​{1}}颜色(可以选择两种颜色),具体取决于来自viewmodel的bool属性。

Path

我认为,我需要使用一些转换器,但不知道如何为它编写XAML代码。像这样的东西?

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

2 个答案:

答案 0 :(得分:1)

路径不是自己的祖先。如果viewmodel是Path的DataContext,那么传统的绑定就足够了:

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

您也可以跳过转换器并使用Style触发器。请注意,此版本中的默认填充不再设置为属性;如果是,那么public suffix list

<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>

答案 1 :(得分:-1)

如果您想使用转换器,可以按照此示例代码制作一个转换器:

1。制作新课程

2. 使用以下命名空间:

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

3. 继承并实施IValueConverter界面

4. Convert函数中,评估value参数并返回您想要的相应颜色

示例代码

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();
    }
}
相关问题