Search code examples
wpfvisibilitykey-bindings

Key Bindings WPF with Caliburn Micro


I have a window with a TabControl. I have a TabItem where I set:

Visibility="{Binding IsVisible}

I have also added this to the XAML of the window:

<Window.InputBindings>
    <KeyBinding Modifiers="Ctrl"
                Key="H"
                Command="{Binding ToggleHiddenTab}" />
</Window.InputBindings> 

I added this method to the ViewModel.

public void ToggleHiddenTab()
        {
            if (IsVisible == Visibility.Visible)
            {
                IsVisible = Visibility.Hidden;
                NotifyOfPropertyChange(() => IsVisible);
            }
            else
            {
                IsVisible = Visibility.Visible;
                NotifyOfPropertyChange(() => IsVisible);
            }
        }

And the full property:

private Visibility _isVisible;
public Visibility IsVisible
        {
            get { return _isVisible; }
            set {
                _isVisible = value;
                NotifyOfPropertyChange(() => IsVisible);
            }
        }

When I press CTRL+h nothing happens. To test the functionality I added a test button:

<Button x:Name="ToggleHiddenTab" Content="Test Visible" 
        Grid.Column="0" Margin="20,8,20,8">
    <Button.Resources>
        <Style TargetType="{x:Type Border}">
            <Setter Property="CornerRadius" Value="5"/>
        </Style>
    </Button.Resources>
</Button>

When I click the button the hidden tab changes its visibility. Why is the ctrl+h key not being accepted?

--------------------- EDIT------------------------------------------- Per the answer below I added:

cal:Message.Attach="[Gesture Ctrl+H] = [ToggleHiddenTab]"

Then the editor thru a "namespace undefined" error for "cal:", a quick google search suggested adding to the window tag:

xmlns:cal="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro.Platform"

This is still not working as suggested.


Solution

  • ToggleHiddenTab is not a command, it's a method.

    But you should be able to use the cal:Message.Attach attached property to hook up the key binding:

    <Window ... cal:Message.Attach="[Gesture Ctrl+H] = [ToggleHiddenTab]">