gpt4 book ai didi

c# - 命令在我的附加属性中获取 null 用于将事件转换为命令

转载 作者:行者123 更新时间:2023-11-30 16:58:34 26 4
gpt4 key购买 nike

我正在使用 mvvm,所以我试图在代码中减少(或可能没有)代码。我想将 TextBox 上的 KeyDown 事件转换为 Command。我正在使用 Interactivity dll我的 Xaml 代码是:

  <TextBox Background="White" Name="txtHigh" AcceptsReturn="False" Height="23" Width="98"  Margin="3" Grid.Column="3" Text="{Binding SelectionHigh, Mode=TwoWay,Converter={StaticResource formatCell}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<commands:EventToCommand Command="{Binding HighValueChangedCmd}" ></commands:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>


转换 EventToCommand 的代码是:

  public class EventToCommand : TriggerAction<FrameworkElement>
{
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}

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


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

// Using a DependencyProperty as the backing store for CommandParameter. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(EventToCommand), new UIPropertyMetadata(null));

protected override void Invoke(object parameter)
{
if (Command == null) return;
if (Command is RoutedCommand)
{
var rc = Command as RoutedCommand;
if (rc.CanExecute(CommandParameter, base.AssociatedObject))
{
rc.Execute(CommandParameter, base.AssociatedObject);
}
}
else
{
if (Command.CanExecute(CommandParameter))
Command.Execute(CommandParameter);
}
}

}

问题出在我的 Invoke 方法中,我正在获取 Command=null..我不明白为什么会这样?并且我只想在 ExecuteCommand 方法中执行逻辑,仅当按下 enter 或 tab 键时。在代码隐藏中,我们可以使用 KeyEventArgs 来做到这一点。

               KeyEventArgs e;        
if (e.Key == Key.Enter || e.Key == Key.Tab)
//logic

我怎样才能在 ExecuteCommand 方法中实现这一点???

最佳答案

也许您应该尝试另一种方法,而不用实现 Interaction 和 EventToCommand。

<TextBox Background="White" Name="txtHigh" AcceptsReturn="False" Height="23" Width="98"  Margin="3" Grid.Column="3" Text="{Binding SelectionHigh, Mode=TwoWay,Converter={StaticResource formatCell}}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding DataContext.HighValueChangedCmd, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
<KeyBinding Key="Tab" Command="{Binding DataContext.HighValueChangedCmd, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" />
</TextBox.InputBindings>
</TextBox>

关于c# - 命令在我的附加属性中获取 null 用于将事件转换为命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25154553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com