更新前的DataGrid值更改-WPF C#MVVM



我正在尝试使用WPF C#MVVM创建CRUD。我有文档类型主控,脚本如下:

我的XAML:

<TextBox
Grid.Column="1"
materialDesign:HintAssist.FloatingOffset="0, -18"
IsReadOnly="False"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
materialDesign:HintAssist.Hint="Document Type"
HorizontalAlignment="Stretch"
FontSize="14"
Margin="0 10 0 20"
Text="{Binding Path=CurrentDocumentType.DocumentTypeName}" />
<DataGrid
x:Name="dgDocumentType"
CanUserAddRows="False"
SelectionUnit="FullRow"
SelectionMode="Extended"
AutoGenerateColumns="False"
IsReadOnly="True"
ItemsSource="{Binding Path=DocumentTypesList, Mode=TwoWay}"
SelectedItem="{Binding Path=SelectedDocumentType, Mode=TwoWay}">
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Foreground" Value="Black" />
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn
Header="ID"
Binding="{Binding Path=IdDocumentType, Mode=TwoWay}"
Visibility="Hidden" />
<DataGridTextColumn
Header="Document Type"
Binding="{Binding Path=DocumentTypeName, Mode=TwoWay}" />
</DataGrid.Columns>
</DataGrid>

这是我的ViewModel:

private DocumentType selectedDocumentType;
public DocumentType SelectedDocumentType
{
get { return selectedDocumentType; }
set
{
selectedDocumentType = value;
CurrentDocumentType = selectedDocumentType;
OnPropertyChanged("SelectedDocumentType");
}
}
private DocumentType currentDocumentType;
public DocumentType CurrentDocumentType
{
get { return currentDocumentType; }
set
{
currentDocumentType = value;
OnPropertyChanged("CurrentDocumentType");
}
}

我使用的是CurrentDocumentType=selectedDocumentType;所以每当数据网格中的行被选中时,我的文本框总是显示选中的值。

问题是,每次我试图更改文本框currentDocument Type中的值时,数据网格中选定的项目也会更改。当我点击更新按钮时,我想更改数据网格中的值,知道吗?谢谢你。

预览图像

默认情况下,TextBox的绑定为TwoWay。如果不想更改源,则需要将其更改为OneWay
<TextBox
Grid.Column="1"
materialDesign:HintAssist.FloatingOffset="0, -18"
IsReadOnly="False"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
materialDesign:HintAssist.Hint="Document Type"
HorizontalAlignment="Stretch"
FontSize="14"
Margin="0 10 0 20"
Text="{Binding Path=CurrentDocumentType.DocumentTypeName, Mode=OneWay}" />

最新更新