Simple WPF IValueConverter and DataTrigger do not work together

I am having problems using a value converter with a data trigger. In some of my code, it seems DataTrigger Pathto apply to the root element, not the element to which the style belongs.

I created a simple test case and I do not understand its behavior. I expect it to Buttonturn red or blue depending on what value is being supplied to the converter DataTrigger, but Buttonit doesn't change at all!

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SimpleWpfApplication"
    x:Class="SimpleWpfApplication.SimpleUserControl"
    ToolTip="UserControl ToolTip">
    <UserControl.Resources>
        <local:SimpleConverter x:Key="SimpleConverter" />
    </UserControl.Resources>
    <Button ToolTip="Button ToolTip">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <DataTrigger
                        Binding="{Binding Path=ToolTip, Converter={StaticResource SimpleConverter}}"
                        Value="Button ToolTip">
                        <Setter Property="Background" Value="Red" />
                    </DataTrigger>
                    <DataTrigger
                        Binding="{Binding Path=ToolTip, Converter={StaticResource SimpleConverter}}"
                        Value="UserControl ToolTip">
                        <Setter Property="Background" Value="Blue" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</UserControl>

And a simple converter:

class SimpleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new InvalidOperationException("SimpleConverter is a OneWay converter.");
    }
}

Why not called Convert? Why Buttoncan't it be red or blue?

+3
source share
1 answer

StackOverflow: datatrigger?

, RelativeSource={RelativeSource Self} :

<DataTrigger Binding="{Binding Path=ToolTip,
                       RelativeSource={RelativeSource Self},
                       Converter={StaticResource SimpleConverter}}" />
+8

Source: https://habr.com/ru/post/1724326/


All Articles