我有一个DataGrid的用户控件。网格受限于StoreSales的可观察集合列表。 StoreSales是一个具有Store Name,Number等属性的类。 所有这些属性都是数据网格上的列。
想要实现: 双击任何行触发ViewModel(Click_command)上的Relay Command我检索该行的storenumber。我能够触发RelayCommand Click_command。
我应该做RelayCommand<string>
之类的事情并从CommandParamter传递商店号,但不知道如何。
提前致谢。
这就是我所拥有的
的Xaml:
<UserControl x:Class="MyProject.StoreList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
xmlns:vm="clr-namespace:Charlie.UI.ViewModel"
xmlns:ch="clr-namespace:Charlie.UI"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<DataGrid IsReadOnly="True" ItemsSource="{Binding Path=StoreList}" AutoGenerateColumns="False" Name="StoreList" >
<DataGrid.Columns>
<DataGridTextColumn Header="#" Binding="{Binding Path=StoreNumber}" />
<DataGridTextColumn Header="StoreName" Binding="{Binding Path=StoreName}"/>
<DataGridTextColumn Header="Total" Binding="{Binding Path=Total, StringFormat=C}"/>
</DataGrid.Columns>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Path=Click_command, Mode=OneWay}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
</Grid>
视图模型:
public RelayCommand Click_command
{
get;
private set;
}
private ObservableCollection<StoreSales> _StoreList;
public ObservableCollection<StoreSales> StoreList
{
get { return _StoreList; }
set
{
_StoreList = value;
RaisePropertyChanged("StoreList");
}
}
//构造函数
public StoreList()
{
this.Click_command = new RelayCommand(() => Execute_me());
}
public void Execute_me()
{
//Do something with store number
}
答案 0 :(得分:2)
要实现这一目标,您有以下几种选择:
StoreNumber
; {Binding SelectedItem.StoreNumber, ElementName=MyDataGrid}
以将号码作为 CommandParamter 传递; PassEventArgsToCommand="True"
并稍微更新命令定义。然后通过访问发件人,您将获得 SelectedItem (我不喜欢这种方法,但它仍然存在); 对于第三个选项(从 MVVM 透视图不太可取),命令应如下所示:
public RelayCommand Click_command
{
get
{
if (this.click_command == null)
{
this.click_command = new RelayCommand<MouseButtonEventArgs>((args) => this.Execute_me(args));
}
return this.click_command;
}
}