У меня есть какая-то фоновая задача, которая выполняется периодически или, если кто-то запускает ее вручную.
Теперь я хочу какой-то вид Progress / Result View, который показывает обработанные данные.Окно должно отображаться постоянно.
Проблема в том, что каждый раз при запуске фоновой задачи создается новый экземпляр модели данных.Итак, как сохранить привязку модели -> ViewModel, даже если модель будет восстановлена?
Я создал несколько очень простых примеров в качестве демонстрации:
Представление:
<Window x:Class="View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:View"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300" Background="Black">
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Foreground="White" HorizontalAlignment="Center" Content="{Binding MainModelText}"/>
</Grid>
</Grid>
Модель представления:
public class ViewModel : INotifyPropertyChanged
{
MainModel _MainModel;
string _MainModelText;
public string MainModelText
{
get { return this._MainModelText; }
set
{
this._MainModelText = value;
OnNotifyPropertyChanged("MainModelText");
}
}
public ViewModel(MainModel mainModel)
{
this._MainModel = mainModel;
this._MainModel.PropertyChanged += _MainModel_PropertyChanged;
}
private void _MainModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(string.Equals(e.PropertyName, "SomeText"))
{
this.MainModelText = _MainModel.SomeText + new Random().Next(1000);
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnNotifyPropertyChanged(string propName)
{
if(this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
Модель:
public class MainModel : INotifyPropertyChanged
{
string _SomeText;
public string SomeText
{
get { return this._SomeText; }
set
{
this._SomeText = value;
OnNotifyPropertyChanged("SomeText");
}
}
public MainModel()
{
this.SomeText = "Its MainModel!";
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnNotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
Business-Logic
public class Logic
{
MainModel _MainModel;
View.MainWindow _Window;
public Logic()
{
this._MainModel = new MainModel();
_Window = new View.MainWindow(new ViewModel(_MainModel));
}
public void Start()
{
_Window.ShowDialog();
}
public void NewAll()
{
this._MainModel = new MainModel();
//working...
this._MainModel.SomeText = "Finished";
}
}
Таким образом, очевидно, что «Завершено» не отображается в окне, поскольку оно установлено на другой экземпляр MainModel.
Так как же обновить ссылку на модель во ViewModel?Что такое лучшая практика для чего-то подобного?
РЕДАКТИРОВАТЬ:
public class Logic
{
MainModel _MainModel;
ViewModel _ViewModel;
View.MainWindow _Window;
public Logic()
{
this._MainModel = new MainModel();
this._ViewModel = new ViewModel(this._MainModel);
_Window = new View.MainWindow(this._ViewModel);
}
public void Start()
{
_Window.ShowDialog();
}
public void NewAll()
{
this._MainModel = new MainModel();
this._ViewModel.Reload(this._MainModel);
//working...
this._MainModel.SomeText = "Finished";
}
}
Добавлено в VM:
internal void Reload(MainModel mainModel)
{
this._MainModel = mainModel;
this._MainModel.PropertyChanged -= _MainModel_PropertyChanged;
this._MainModel.PropertyChanged += _MainModel_PropertyChanged;
}