本篇主要学习MVVMLight中RelayCommand和如何将Blend中自带的EventToCommand行为应用到RelayCommand中。下面是实例代码。
(1)在MainPage.xaml中写下如下代码。设置Grid的AllowDrop="True",代码如下
<Grid x:Name="LayoutRoot"
AllowDrop="True"
Background="#FF9F9F9F">
<TextBlock FontSize="36"
FontWeight="Bold"
Foreground="Purple"
Text="{Binding DroppedFileContent}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"
TextTrimming="WordEllipsis" />
</Grid>
(2)在MainViewModel.cs中定义DroppedFileContent属性和RelayCommand属性
private const string DroppedFileContentPropertyName = "DroppedFileContent";
private string _droppedFile = "Drop file here";
public string DroppedFileContent
{
get
{
return _droppedFile;
}
set
{
if (_droppedFile == value)
{
return;
}
_droppedFile = value;
RaisePropertyChanged(DroppedFileContentPropertyName);
}
}
public RelayCommand<DragEventArgs> HandleDropCommand
{
get;
private set;
}
(3)在MainViewModel.cs中的构造函数中添加,实现RelayCommand,并定义读取文件方法
public MainViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
}
else
{
HandleDropCommand = new RelayCommand<DragEventArgs>(MessageBoxShow);
}
}
public void MessageBoxShow(DragEventArgs e)
{
//MessageBox.Show("Drop");
if (e.Data == null)
{
return;
}
var files = e.Data.GetData(DataFormats.FileDrop)
as FileInfo[];
// This works with multiple files, but in that
// simple case, let's just handle the 1st one
if (files == null
|| files.Length == 0)
{
DroppedFileContent = "No files";
return;
}
var file = files[0];
if (!file.Extension.ToLower().Equals(".txt"))
{
DroppedFileContent = "Not a TXT file";
return;
}
using (var stream = file.OpenRead())
{
using (var reader = new StreamReader(stream))
{
// Read the first line
var line = reader.ReadLine();
DroppedFileContent = line;
}
}
}
(4)让EventToCommand与RelayCommand关联。
(A)用Blend的方式完成:设置ElementName为Drop,并勾选PassEventArgsToCommand为True.
点Command后弹出上面的菜单,并点击"Data Binding"菜单相,会弹出如下对话框,选择"Data Context"中的HandleDropCommand:[RelayCommand<DragEventArgs>]
设置完成后出现如下显示,Command显示黄色
(B)如果你没有Blend,直接用VS2010完成
在MainPage.xaml中添加两个命名空间
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4"
在MainPage.xaml中的Grid中添加如下代码
<i:Interaction.Triggers>
<i:EventTrigger EventName="Drop">
<cmd:EventToCommand Command="{Binding HandleDropCommand, Mode=OneWay}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
参资资料
http://blog.galasoft.ch/archive/2009/12/17/silverlight-4-dragampdrop-with-eventtocommand.aspx
在线演示