I'm trying to create CRUD using WPF C# MVVM. I have Document Type Master with script like below:
my 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>
And this is my 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");
}
}
i'm using CurrentDocumentType = selectedDocumentType; so my textbox always show selected value everytime row in datagrid selected.
The problem is everytime i try to change value in textbox currentDocument Type, selected item in datagrid changes too. i want value in datagrid change when i hit update button, any idea? thanks before.
CodePudding user response:
Binding for TextBox
is TwoWay
by default. You need to change it to OneWay
if you don't want to change the source.
<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}" />