Search code examples
c#wpfdatatrigger

How to use a datatrigger that needs a static global variable?


I have a static class that has a static property that I need to set the visilibity of a button.

I am trying something like that:

<Button.Style>
                                <Style TargetType="Button">
                                    <Setter Property="Visibility" Value="Collapsed"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding ElementName=x:Static vg:GlobalResources.MyProperty, Path=IsAdmin}" Value="True">
                                            <Setter Property="Visibility" Value="Visible"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Button.Style>

Also, in the header of the xaml I include the name space:

xmlns:vg="clr-namespace:MyApplication.resources"

But when the property IsAdmin is true, the button is not visible.

I have tried another options like this:

<DataTrigger Binding="{Binding ElementName=x:Static vg:GlobalResources, Path=MyProperty.IsAdmin}" Value="True">

But it doesn't solve the problem.

So, how could I use the global variable?

Thanks.


Solution

  • Use the Source property of the Binding, i.e.

    <DataTrigger Binding="{Binding Source={x:Static vg:GlobalResources.MyProperty}, Path=IsAdmin}" Value="True">
    

    Important: IsAdmin must be either a dependency property or it must fire INotifyPropertyChanged.PropertyChanged when it is changed.

    Since WPF 4.5 there is also this syntax for binding to static properties:

    Binding="{Binding Path=(vg:GlobalResources.MyProperty).IsAdmin}"