Question

<DataTemplate x:Key="dataTempl">
            <!--<Border BorderBrush="Coral" BorderThickness="1" Width="Auto" Margin="2">-->
            <Button Background="{Binding background}" Name="btn" Tag="{Binding oID}" Click="btn_Click"  Style="{StaticResource MetroButton}" Margin="1">
                (... rest of items here ...)
                </StackPanel>
            </Button>
            <!--</Border>-->
        </DataTemplate>

As you can see, button have Style and background. Style from Resources contain border, background (as gradient) etc. Now background element from my class:

 public Brush background
        {
            get
            {
                SolidColorBrush clr = null;
                if (backgroundString != "")
                {
                    clr = new SolidColorBrush((Color)ColorConverter.ConvertFromString(backgroundString));

                }
                 return clr;

            }
        }

But problem is that, it could contains color like #FFFF0000 or just be null. What I'd like to do is :

if (backgroundString != "") -> apply background

else leave style as it was before.

But with code I show you, if it return null, style does change (there is no borders etc.)

Any idea?

Thanks!

Was it helpful?

Solution

What you want to do is a trigger.

You would like to use the default background, but override it when a given property meet a given condition. You can do this easily with a trigger.

Simply add a property such as this one to your view model:

public bool OverrideBackground { get { return backgroundString != ""; } }

Then add the following trigger in your DataTemplate:

<DataTemplate>
    [...] 
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding OverrideBackground}" Value="true">
            <Setter Property="Button.Background" Value="{Binding background}" TargetName="btn"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

The DataTrigger will be activated when the OverrideBackground property is true (that is, when backgroundString != ""), and will set the Background property of the Button (that you named btn in your code snippet) to the value of the background property of the bound view model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top