我想控制我的 c# WPF 应用程序窗口中按钮的可见性。
. 只有当用户点击“alt+a+b”时,该按钮才可见。如果用户点击“alt+a+c”,按钮应该不可见。我该怎么做。知道吗?
我想控制我的 c# WPF 应用程序窗口中按钮的可见性。
. 只有当用户点击“alt+a+b”时,该按钮才可见。如果用户点击“alt+a+c”,按钮应该不可见。我该怎么做。知道吗?
就个人而言,我会创建一个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. Button为此,我们需要实现IValueConverter布尔值和值之间的转换Visibility。
[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;
    }
}
现在,我们只需要绑定到 XAMLButton声明中的布尔属性:
<Button Visibility="{Binding IsButtonVisible, 
    Converter={StaticResource BoolToVisibilityConverter}, 
    FallbackValue=Collapsed, Mode=OneWay}">
    表单上的 KeyDown 或 KeyPress 事件?
订阅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
    }
}