我想使用命令在文本框中实现KeyDown事件,
我想让命令能够识别KeyEventArgs中的哪些键输入在KeyDown事件中执行并执行其他操作,
所以我想将命令参数传递给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>
并且两个类代码首先是视图,第二个是viewmodel:
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");
}
);
}
}
接下来该怎么做才能将文本框KeyInput作为参数传递给命令?
答案 0 :(得分:0)
您可以自行传递文本框,也可以只传递文本。我不知道你想用它做什么,但如果你必须与文本框进行交互,那么我建议你自己传递文本框:
传递文字:
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding OpenFCmd}"
CommandParameter="{Binding ElementName=Box, Path=Text}" />
</i:EventTrigger>
</i:Interaction.Triggers>
传递textBox:
<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;
}
答案 1 :(得分:0)
将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>