反应命令传递命令参数
本文关键字:命令 参数 | 更新日期: 2023-09-27 18:32:53
我想使用命令在文本框中实现KeyDown 事件,
我想让命令可以识别哪些键输入(如 KeyEventArgs)在 KeyDown Event 中执行哪些操作并执行其他一些操作,
所以我想将命令参数传递给 ReactiveCommand(就像 Eventargs 在事件方法中所做的那样),
但我不知道该怎么做。
我有WPF Xaml代码:
<Window x:Class="NameSpaceTest.OpenFileW"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:command="http://www.galasoft.ch/mvvmlight"
Title="OpenFileWVieModel" Height="50" Width="200" WindowStyle="None">
<Grid>
<TextBox Name="Box" Text="{Binding OpenFPth, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding OpenFCmd}" CommandParameter=""/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</Grid>
</Window>
两个类代码首先是视图,其次是视图模型:
public partial class OpenFileW : Window
{
OpenFileWVieModel OFVM = new OpenFileWVieModel();
public OpenFileW()
{
this.DataContext = OFVM;
InitializeComponent();
}
}
public class OpenFileWVieModel : ReactiveObject
{
public string OpenFPth { get { return _openFpth; } set { this.RaiseAndSetIfChanged(ref _openFpth, value); } }
private string _openFpth;
public IReactiveCommand OpenFCmd { get; set; }
public OpenFileWVieModel()
{
var TextChange = this.WhenAny(
x => x.OpenFPth,
x =>
{
MessageBox.Show("HI");
return true;
});
OpenFCmd = ReactiveCommand.CreateAsyncTask(
TextChange, //CanExecute
async _ =>//Execute
{
MessageBox.Show("HI");
}
);
}
}
接下来要怎么做才能将文本框键输入作为参数传递给命令?
您可以自行
传递文本框或仅传递文本。我不知道你想用它做什么,但是如果你必须与文本框交互,那么我建议自己传递文本框:
传递文本:
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding OpenFCmd}"
CommandParameter="{Binding ElementName=Box, Path=Text}" />
</i:EventTrigger>
</i:Interaction.Triggers>
传递文本框:
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding OpenFCmd}"
CommandParameter="{Binding ElementName=Box}" />
</i:EventTrigger>
</i:Interaction.Triggers>
编辑:
使用上面的代码,您可以在代码中创建事件处理程序:
void OpenFCmn_OnClick(object obj)
{
var tb = (TextBox) obj;
tb.KeyDown += TbOnKeyDown;
}
private void TbOnKeyDown(object sender, KeyEventArgs keyEventArgs)
{
MessageBox.Show(keyEventArgs.Key.ToString());
keyEventArgs.Handled = true;
}
将 KeyDown 事件绑定到视图模型的命令并设置 PassEventArgsToCommand="True" 这会将 KeyDown 事件的参数传递给您的命令。
<TextBox VerticalAlignment="Top" Width="120">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding KeyDownCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>