最简单的解决方案是为两个窗口使用共享的DataContext 实例,并使用ICommand 将新的Account 项目实际添加到集合中:
RelayCommand.cs
实现取自Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern - Relaying Command Logic
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute) : this(execute, null) { }
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute; _canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter) { _execute(parameter); }
#endregion // ICommand Members
}
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
this.NewAccount = new Account();
this.ListAccountInfo = new ObservableCollection<Account>()
{
new Account
{
IsSelected = true,
Username = "test123",
qweqwe = "test123",
qwe = "N/A",
qwe = "N/A",
qwe = "N/A",
qwe = "N/A",
qwe = "N/A",
qwe = "N/A"
}
};
}
public ObservableCollection<Account> ListAccountInfo { get; }
private Account newAccount;
public Account NewAccount
{
get => this.newAccount;
set
{
this.newAccount = value;
OnPropertyChanged();
}
}
public ICommand AddAccountCommand
{
get => new RelayCommand(
param =>
{
this.ListAccountInfo.Add(this.NewAccount);
this.NewAccount = new Account();
});
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion Implementation of INotifyPropertyChanged
}
App.xaml
<Application>
<Application.Resources>
<!-- Globally shared ViewModel instance -->
<ViewModel x:Key="ViewModel" />
</Application.Resources>
</Application>
MainWindow.xaml
<Window>
<Window.DataContext>
<StaticResource ResourceKey="ViewModel" />
</Window.DatContext>
<DataGrid ItemsSource="{Binding ListAccountInfo}" />
</Window>
DialogWindow.xaml
<Window.DataContext>
<StaticResource ResourceKey="ViewModel" />
</Window.DatContext>
<StackPanel>
<TextBox Text="{Binding NewAccount.Username}" />
<Button Content="Add"
Command="{Binding AddAccountCommand}" />
</StackPanel>
</Window>