带有关键组件命令的自定义键盘未通过

Custom keyboard with key components commands not feeding through

我正在创建一个自定义屏幕键盘,以在我的程序中保持外观一致。 我决定让每个键都是一个自定义组件,它将托管在 Keyboard 组件上的命令提供给 Key 的按钮部分。这样我也可以为特殊键使用相同的 Key 组件。

Key 组件在直接托管在主要 window 上时工作正常,但是当我尝试通过 Keyboard 组件 运行 它时,该命令没有执行。

目的是将 Key 上的字母或数字添加到键盘的 Text 属性 上。以后再处理特殊键。

Key 片段:

<UserControl
    x:Name="ThisKey"
    >
    <Grid>
        <Button
            Command="{Binding Command, ElementName=ThisKey}"
            CommandParameter="{Binding CommandParameter, ElementName=ThisKey}"
            />
    </Grid>
</UserControl>

其中 CommandCommandParameter 定义为:

public ICommand Command
{
    get => (ICommand)GetValue(CommandProperty);
    set => SetValue(CommandProperty, value);
}

public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
    nameof(Command),
    typeof(ICommand),
    typeof(Key),
    new UIPropertyMetadata(null));

public object CommandParameter
{
    get => GetValue(CommandParameterProperty);
    set => SetValue(CommandParameterProperty, value);
}

public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
    nameof(CommandParameter),
    typeof(object),
    typeof(Key),
    new PropertyMetadata(string.Empty));

Keyboard 组件中,我调用 Keys 如下:

<local:Key
    Command={Binding KeyCommand, RelativeSource={RelativeSource AncestorType=local:Keyboard}}"
    CommandParameter="0"
    />

其中 KeyCommand 定义为:

private RelayCommand KeyCommandRelay;
public ICommand KeyCommand
{
    get
    {
        if (KeyCommandRelay == null)
        {
            KeyCommandRelay = new RelayCommand(
                    param => KeyCommand_Executed(param),
                    param => true
                    );
        }
        return KeyCommandRelay;
    }
}
private void KeyCommand_Executed(object param)
{
    //Text is a string property of Keyboard.
    Text += (string)param;
    //This is here to prove to me that the button is pressed, to rule out errors with Text.
    MessageBox.Show((string)param);
}

Key 直接放在 window 中可以使命令正常工作,但是在构成 Keyboard 的一部分时不会执行命令。

我意识到我在键盘上重命名了命令,但没有在 XAML 中重命名。除此之外,我还用“KeyButtom”而不是原来的名字“Keybutton”打错了它。