Search code examples
wpfstylesdatatrigger

How to style a button based on a property of the window


I have a simple WPF application with a Window. This window has a dependency property.

    public static readonly DependencyProperty ShiftProperty;

    static VirtualKeyboard()
    {
        ShiftProperty = DependencyProperty.Register("Shift", typeof(bool), typeof(VirtualKeyboard));
    }

    public bool Shift
    {
        get { return (bool)GetValue(ShiftProperty); }
        set { SetValue(ShiftProperty, value); }
    }

Now, on this window I have a button that I wish to visually display if Shift is True or not, by applying a style.

I admit to not being very experienced in WPF, but I believe this can be solved using Data triggers. My problem is hooking it up.

Here is the xaml for the button.

        <Button Grid.Row="4" Grid.ColumnSpan="2" Grid.Column="0" Command="local:VirtualKeyboard.ShiftButtonPressedCommand" Content="Shift" Name="ShiftButton">
            <Button.Style>
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=Shift}" Value="True">
                            <Setter Property="Control.Background" Value="Black">

                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

I'll appreciate all help I can get.

Thanks, Stefan


Solution

  • You are right.You can do it with datatriggers.You need to set the datacontext of the widow to this for this to work.Otherwise the binding will not be able to access your dependency property.

        public VirtualKeyboard()
        {
            InitializeComponent();
            DataContext = this;
        }
    

    and specify your style like

     <Button  Grid.Column="0" Content="Shift" Name="ShiftButton">
                <Button.Style>
                    <Style>
                        <Setter Property="Button.Visibility" Value="Collapsed"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Shift}" Value="True">
                                <Setter Property="Button.Visibility" Value="Visible">
                                </Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Button.Style>
            </Button>