Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 420
mjk6026 Avatar asked Aug 06 '11 18:08

mjk6026


3 Answers

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" />
like image 149
Tim Richards Avatar answered Nov 01 '22 07:11

Tim Richards


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

like image 24
Emond Avatar answered Nov 01 '22 08:11

Emond


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.

like image 5
WPF-it Avatar answered Nov 01 '22 07:11

WPF-it