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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top