双击WPF行后,填充第二个DataGrid

时间:2013-06-19 13:44:57

标签: wpf events datagrid wpfdatagrid delegatecommand

我对wpf和MVVM还有点新意。我试图在不破坏该模式的情况下编写解决方案。我有两个(三个,但这个问题的范围只有两个)DataGrid s。我想双击一行的一行,并从那个加载数据到第二个DataGrid(理想情况下我会启动第二个加载数据的线程)。到目前为止,当我双击一行时,我可以弹出一个窗口。我将事件的代码放入xaml的代码中。对我来说,似乎非常窗户形式。不知何故,我觉得这样做打破了很多模式。

private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) {
    if (popDataGrid.SelectedItem == null) {
        return;
    }
    var selectedPopulation = popDataGrid.SelectedItem as PopulationModel;
    MessageBox.Show(string.Format("The Population you double clicked on has this ID - {0}, Name - {1}, and Description {2}", selectedPopulation.populationID, selectedPopulation.PopName, selectedPopulation.description));
}

这是后面代码中事件的代码,这里是xaml中的网格定义:

<DataGrid ItemsSource="{Binding PopulationCollection}" Name="popDataGrid"
          AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected"
          CanUserAddRows="False" Margin="296,120,0,587" HorizontalAlignment="Left" Width="503" Grid.Column="1" 
          MouseDoubleClick="DataGrid_MouseDoubleClick">
</DataGrid>

我认为这段代码应该放在MainWindowViewModel中。所以我试图创建一个命令:

public ICommand DoubleClickPopRow { get { return new DelegateCommand(OnDoubleClickPopRow); }}

和相同的事件处理程序:

private void OnDoubleClickPopRow(object sender, MouseButtonEventArgs e) {
}

ICommand在返回DelegateCommand(OnDoubleClickPopRow)时会抛出异常。

好吧,人们可以清楚地看到参数的数量不匹配。我知道我做错了什么,但我不太确定它是什么。我会继续研究这个,但是你们给予的任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<DataGrid ItemsSource="{Binding PopulationCollection}" Name="popDataGrid"
AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected"
CanUserAddRows="False" Margin="296,120,0,587" HorizontalAlignment="Left" Width="503"  Grid.Column="1" SelectedItem="{Binding ItemInViewModel}"></DataGrid>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding Save_Bid}" />
</i:EventTrigger>
</i:Interaction.Triggers>

您可以将其添加到DataGrid并在视图模型中添加代码。 现在我们有一个选定的项目绑定到我们的视图模型中的项目,我们可以使用该项目来了解我们何时可以触发我们想要的以及在事件被触发时使用的项目当事件可以被触发时

bool Can_Fire_Event()
{
if(ItemInViewModel != null)
{ return true; } else { return false; }
}
private RelayCommand _saveBid;
public ICommand SaveBid
{
get
{
if (_saveBid == null)
{
_saveBid = new RelayCommand(param => Save_Bid(), param => Can_Fire_Event());
}
return _saveBid;
}
}

public void Save_Bid()
{
//Open your new Window here, using your "ItemInViewModel" because this event couldn't be fired from your datagrid unless the "ItemInViewModel" had a value assigned to it

}