gpt4 book ai didi

c# - WPF 数据网格 : Save cell changes immediately with MVVM

转载 作者:行者123 更新时间:2023-12-02 07:06:54 30 4
gpt4 key购买 nike

我有一个简化的 DataGrid,如下所示:

<DataGrid AutoGenerateColumns="False" 
ItemsSource="{Binding Parts}"
SelectedItem="{Binding SelectedPart}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name, Mode=TwoWay}" />
<DataGridTemplateColumn Header="PartType" >
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.PartTypes}"
SelectedItem="{Binding PartType, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding PartType}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

我的 ViewModel 看起来像这样:

public class PartListViewModel
{
private ObservableCollection<Part> _parts;
public ObservableCollection<Part> Parts
{
get { return _parts; }
set
{
_parts = value;
OnPropertyChanged("Parts");
}
}

private Part _selectedPart;
public Part SelectedPart
{
get { return _selectedPart; }
set
{
_selectedPart = value;
OnPropertyChanged("SelectedPart");
}
}
}

现在我希望对数据网格单元格的更改立即存储到数据库中。如何在 MVVM 中做到这一点?

目前,我监听 DataGrid 的 OnCellEditEnding 事件并将记录保存在代码隐藏中。但这非常难看:

private void DataGrid_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
var viewModel = (PartListViewModel) DataContext;
viewModel.SavePart((Part) e.Row.Item);
}

最佳答案

你可以做这样的事情。(您需要添加对 System.Windows.Interactivity 的引用, you can download the assemblies from here )

然后在 XAML 中添加对命名空间的引用。xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<i:Interaction.Triggers>
<i:EventTrigger EventName="CellEditEnding">
<i:InvokeCommandAction Command="{Binding SomeCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>

关于c# - WPF 数据网格 : Save cell changes immediately with MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554993/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com