自定义键盘的关键组件命令不通过



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

直接托管在主窗口上时,Key组件工作良好,但当我尝试通过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直接放置在窗口中可以使命令正常工作,但在形成Keyboard的一部分时不会执行命令。

我意识到我已经重命名了键盘上的命令,但没有在XAML中重命名它。除此之外,我还把它打错了";KeyButtom";而不是原来的名称";按键";。

最新更新