Pinotek Pinotek - 2 months ago 5
C# Question

DataTemplate don't change Image

<DataTemplate>
<Image Name="ServerImageSetter" Source="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test1.svg}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding ServerKindTrigger}" Value="0">
<Setter TargetName="ServerImageSetter" Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test2.svg}"/>
</DataTrigger>
<DataTrigger Binding="{Binding ServerKindTrigger}" Value="1">
<Setter TargetName="ServerImageSetter" Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test3.svg}"/>
</DataTrigger>
<DataTrigger Binding="{Binding ServerKindTrigger}" Value="2">
<Setter TargetName="ServerImageSetter" Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test3.svg}"/>
</DataTrigger>
</DataTemplate


In my C# code I switch the kind of my value to 0-2 and that should change the image. But the change doesn't work.

public int ServerKindTrigger
{
get { return _serverKindTrigger; }
set { _serverKindTrigger = value;
RaisePropertyChanged();
}
}

//Here I switch my serverkind and wanna change the image value

switch (_serverKind)
{
case Servers.test: _serverKindTrigger = 0;

Answer

Besides setting the backing field _serverKindTrigger instead of the property ServerKindTrigger, and thus not firing the PropertyChangedEvent, you are directly setting the Source property of the Image control:

<Image Source="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test1.svg}"/>

This so-called local value always has a higher precedence than the values from the Setters in the DataTriggers. For reference, see Dependency Property Value Precedence.

Change your XAML to this:

<Image>
    <Image.Style>
        <Style TargetType="Image">
            <Setter Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test1.svg}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ServerKindTrigger}" Value="0">
                    <Setter Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test2.svg}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ServerKindTrigger}" Value="1">
                    <Setter Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test3.svg}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ServerKindTrigger}" Value="2">
                    <Setter Property="Source" Value="{svg2Xaml:SvgImage ServerAdministrator2;component/Images/test3.svg}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
Comments