mjk6026
mjk6026

Reputation: 1484

Trigger Condition when Not an Empty String

We can check some control's string property which has been empty like following code:

<Trigger SourceName="atCaption" Property="Text" Value="{x:Static sys:String.Empty}">
    <Setter TargetName="imgBack" Property="Margin" Value="0"/>
    <Setter TargetName="atCaption" Property="Margin" Value="0"/>
</Trigger>

but, how can one define a condition which is based on a 'not empty' string?

<!--unfortunately, can't accept '!=' operator in xaml.-->
<Trigger SourceName="atCaption" Property="Text" Value!="{x:Static sys:String.Empty}">
    <Setter TargetName="imgBack" Property="Margin" Value="0"/>
    <Setter TargetName="atCaption" Property="Margin" Value="0"/>
</Trigger>

Upvotes: 15

Views: 20554

Answers (4)

Tim Richards
Tim Richards

Reputation: 99

to augment the answer by WPF-it (to me this is a permanent solution, not a quick fix)

    <DataTrigger Binding="{Binding VolumeGroup}" Value="{x:Null}">
        <Setter Property="Background" Value="{StaticResource DataGridBackground}" />
    </DataTrigger>
    <DataTrigger Binding="{Binding VolumeGroup}" Value="">
        <Setter Property="Background" Value="{StaticResource DataGridBackground}" />
    </DataTrigger>
</Style.Triggers>
<!--inverted rare case: VolumeGroup will usually be empty so cells will be {StaticResource DataGridBackground}-->
<Setter Property="Background" Value="DarkOliveGreen" />

Upvotes: 9

Vinit Sankhe
Vinit Sankhe

Reputation: 19885

To quickly get around with thus, the values that apply to the reverse condition should be defaulted in the element declaration or the Style and then use the straight equality condition to alter values.

e.g.

Assume if margin 5 is what you set for empty string and 0 is what you have to set for non empty string then you will set 0 by default as a simple Setter in Style and then check for empty string using Trigger and set 5. Make sure that the default Setter (for 0) appears before Trigger (for 5) in the Style.

Upvotes: 6

Emond
Emond

Reputation: 50682

Using a ValueConverter is a solution.

When using MVVM you could consider an extra property on the ViewModel class you are binding to that determines how a control should be displayed.

When I use the MVVM-way of solving this I don't need a trigger, I simply add extra properties to the ViewModel and bind the View's properties to these extra properties to manipulate the View

Upvotes: 6

scptre
scptre

Reputation: 334

If you use a data trigger it uses a binding syntax so you can use a IValueConverter class to convert to property into a boolean value. You can write the check that you want to take place in code inside a custom IValueConverter.

Upvotes: 0

Related Questions