There is a Contractor.xaml with DataContext:
<Window.DataContext> <local:ViewModel /> </Window.DataContext>
There is a ContractorDetail.xaml with a DataContext:
<Window.DataContext> <local:ContractWindowViewModel /> </Window.DataContext>
The first window displays general information, the second displays all fields with the possibility of editing, the transition is carried out as follows (The selected Contractor is transmitted):
public void OpenContractorDetailView(object param) { var contractor = param is ContractorType ? param as ContractorType : null; if(contractor != null) { var contractorDetailsView = new ContractorDetailsWindow(); var vm = contractorDetailsView.DataContext is ContractorDetailsWindowViewModel ? contractorDetailsView.DataContext as ContractorDetailsWindowViewModel : null; vm.Contractor = contractor; contractorDetailsView.Owner = Application.Current.MainWindow; contractorDetailsView.WindowStartupLocation = WindowStartupLocation.CenterOwner; contractorDetailsView.ShowDialog(); } }
The Details button is created in code behind Contractor.xaml.cs. Here is the code:
var vm = this.DataContext is PackageWindowViewModel ? this.DataContext as PackageWindowViewModel : null; var messageType = vm.MessageType; foreach(var contractor in messageType.Contractors) { ... Button ownerDetails = new Button() { Content = "Детали...", Width = 100, Height = 23, Margin = new Thickness(0, 5, 5, 0), HorizontalAlignment = HorizontalAlignment.Right, Command = new RelayCommand(arg => vm.OpenContractorDetailView(contractor), can => true) }; ...
As a result, when I edit the fields in a modal window, they change in the main window.
The binding in ContractorDetail is done as follows (In the example, one field of the Contractor object, the other fields are bound as well):
<TextBox Grid.Column="1" Grid.Row="6" Text="{Binding Path=Contractor.OKTMO, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" Margin="2" />
Save button:
<Button Grid.Row="9" Grid.Column="1" Content="Сохранить" Width="100" Height="25" HorizontalAlignment="Right" Margin="0, 10, 120, 0" Command="{Binding SaveContractorCommad, Mode=OneWay}" />
The SaveContractorCommad command is bound to the method: SaveContractorMethod
private void SaveContractorMethod() { //OnPropertyChanged("Contractor"); }
ViewModel with property and field in ContractWindowViewModel:
private ContractorType _contractor; public ContractorType Contractor { get { return _contractor; } set { _contractor = value; OnPropertyChanged("Contractor"); } }
Question: How to make it so that when the Contractor object changes its value through the TextBox, these changes are applied only by clicking the Save button, and nothing happens when the window is canceled or closed?