Control the visibility of my button using the COntrol key

I want to control the visibility of my button in the window of my WPF C # application.

. The button should be valid only if the user presses "alt + a + b" .and buton shoulkd be invisible if the user presses "alt + a + c". How can i do this. Any idea?

+4
source share
4 answers

Personally, I would create a boolean property called IsButtonVisible in my view model, which implements the INotifyPropertyChanged interface.

Then I would add some kind of handler method to handle keystrokes ( KeyDown ):

 if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) // Is Alt key pressed { IsButtonVisible = Keyboard.IsKeyDown(Key.A) && Keyboard.IsKeyDown(Key.B); } 

Now the IsButtonVisible property will be updated when the key is pressed correctly, we just need to use this value to affect the Visibility Button property. To do this, we need to implement IValueConverter to convert between a boolean value and a Visibility value.

 [ValueConversion(typeof(bool), typeof(Visibility))] public class BoolToVisibilityConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || value.GetType() != typeof(bool)) return null; bool boolValue = (bool)value; return boolValue ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || value.GetType() != typeof(Visibility)) return null; return (Visibility)value == Visibility.Visible; } } 

Now we just need to bind to our Boolean property from the XAML Button declaration:

 <Button Visibility="{Binding IsButtonVisible, Converter={StaticResource BoolToVisibilityConverter}, FallbackValue=Collapsed, Mode=OneWay}"> 
+2
source

KeyDown event or KeyPress event in your form?

+1
source
  • Associates button visibility with your ViewModel
  • Create a team that is tied to the highest level of your application (MainWindow)
  • Assign the desired hotkey for your team
  • During the command, change the value of the property that you used in step # 1
  • Do the same for the other command (one for visible another for invisible)
0
source

Sign up for the KeyDown your WPF window. Then do the following:

 private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.KeyboardDevice.IsKeyDown(Key.LeftAlt) && e.KeyboardDevice.IsKeyDown(Key.A) && e.KeyboardDevice.IsKeyDown(Key.B)) { // Do your stuff here } } 
0
source

Source: https://habr.com/ru/post/1492920/


All Articles