【发布时间】:2026-02-06 06:10:01
【问题描述】:
我有一个带有 DataGrid 的用户控件。 Grid 绑定到 StoreSales 的可观察集合列表。其中 StoreSales 是一个具有商店名称、编号等属性的类。 所有这些属性都是数据网格上的列。
想要实现: 在任何行的双击触发 ViewModel(Click_command) 上的中继命令是我检索该行的商店编号。我能够触发 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
}
【问题讨论】:
-
另一种方法是使用不带参数的命令,但在数据网格中使用 SelectedItem 绑定。那么当您处理双击时,您的视图模型就会知道“双击”行
标签: c# xaml mvvm-light wpfdatagrid