我需要将此事件从用户控件移动到viewModel,我已阅读以下链接 但不确定我得到它,因为命令是真还是假,我的问题是假设我有以下事件 我应该如何将其更改为viewModel。
请协助,我真的卡住!!!!
http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
private void DropText_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
var textBox = (TextBox) sender;
if (textBox == null) return;
textBox.Focus();
var dataObject = new DataObject((textBox).Text);
dataObject.SetData(DragSource, sender);
DragDrop.DoDragDrop(textBox, dataObject, DragDropEffects.Copy | DragDropEffects.Move);
}
<TextBox x:Name="Job"
AcceptsReturn="True"
AllowDrop="True"
PreviewMouseDown="DropText_PreviewMouseDown"
SelectionChanged="listbox_SelectionChanged"
HorizontalAlignment="Left"
internal class RelayCommand : ICommand
{
readonly Action _execute;
readonly Func<bool> _canExecute;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (_canExecute != null)
CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
_execute();
}
public event EventHandler CanExecuteChange;
public void RaiseCanExecuteChange()
{
if (CanExecuteChange != null)
CanExecuteChange(this, new EventArgs());
}
答案 0 :(得分:0)
以下是您在xaml中定义事件触发器的示例。 PreviewMouseDownCommand和SelectionChangedCommand是需要在viewmodel中声明的RelayCommands。
<TextBox x:Name="Job"
AcceptsReturn="True"
AllowDrop="True"
HorizontalAlignment="Left">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown" >
<i:InvokeCommandAction Command="{Binding PreviewMouseDownCommand}" />
</i:EventTrigger>
<i:EventTrigger EventName="SelectionChanged" >
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
您需要对System.Windows.Interactivity的引用才能使用事件触发器。将其添加到窗口中的命名空间声明中:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"