使用COntrol键控制我的按钮的可见性

时间:2013-07-23 10:32:09

标签: c# wpf windows-applications

我想在我的c#WPF应用程序的窗口中控制我的按钮的可见性。

。只有当用户点击“alt + a + b”时,该按钮才能保持不变。如果用户点击“alt + a + c”,则该按钮不可见。我怎么能这样做。任何想法?

4 个答案:

答案 0 :(得分:2)

就个人而言,我会在我的视图模型中创建一个名为IsButtonVisible的布尔属性,该属性实现INotifyPropertyChanged接口。

然后我会添加一些处理程序方法来处理按键(KeyDown事件):

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

现在IsButtonVisible属性将在正确按键时更新,我们只需要使用此值来影响Visibility的{​​{1}}属性。为此,我们需要实现Button以在布尔值和IValueConverter值之间进行转换。

Visibility

现在,我们只需要从XAML [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; } } 声明绑定到我们的Boolean属性:

Button

答案 1 :(得分:1)

表单上的KeyDown或KeyPress事件?

答案 2 :(得分:0)

  1. 将Button的可见性绑定到ViewModel
  2. 创建一个绑定到最顶级应用程序(MainWindow)的命令
  3. 将所需的热键分配给您的命令
  4. 在命令执行期间更改您在步骤#1中使用的属性值
  5. 对另一个命令执行相同的操作(一个用于可见的另一个命令)

答案 3 :(得分:0)

订阅KeyDown窗口的WPF事件。然后这样做:

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
    }
}
相关问题