persisting view models

This commit is contained in:
Holger Börchers 2020-02-18 22:07:39 +01:00
parent b910d3a1e6
commit 6ba9c57bd0
3 changed files with 104 additions and 14 deletions

View File

@ -1,6 +1,8 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.IO; using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text.Json; using System.Text.Json;
using System.Windows; using System.Windows;
@ -11,7 +13,13 @@ namespace ModernWpfPlayground
{ {
public abstract class BaseViewModel : INotifyPropertyChanged public abstract class BaseViewModel : INotifyPropertyChanged
{ {
protected BaseViewModel()
{
_properties = GetType().GetProperties();
}
private readonly Dictionary<string, object> _valueDict = new Dictionary<string, object>(); private readonly Dictionary<string, object> _valueDict = new Dictionary<string, object>();
private readonly PropertyInfo[] _properties;
protected bool SetProperty<T>(T value, [CallerMemberName] string propertyName = null) protected bool SetProperty<T>(T value, [CallerMemberName] string propertyName = null)
{ {
@ -39,7 +47,7 @@ namespace ModernWpfPlayground
public void SaveViewModel() public void SaveViewModel()
{ {
var contents = JsonSerializer.Serialize(_valueDict); var contents = JsonSerializer.Serialize(_valueDict);
var saveFileDialog = new SaveFileDialog(); var saveFileDialog = new SaveFileDialog {AddExtension = true, DefaultExt = "*.json"};
var result = saveFileDialog.ShowDialog(Application.Current.MainWindow?.Owner); var result = saveFileDialog.ShowDialog(Application.Current.MainWindow?.Owner);
if (result == true) if (result == true)
{ {
@ -47,15 +55,59 @@ namespace ModernWpfPlayground
} }
} }
public void LoadViewModel(string path) public void ResetViewModel()
{ {
var contents = File.ReadAllText(path); foreach (var key in _valueDict.Keys)
var obj = JsonSerializer.Deserialize<Dictionary<string, object>>(contents);
foreach (var (key, value) in obj)
{ {
_valueDict[key] = value; _valueDict.Remove(key);
OnPropertyChanged(key); OnPropertyChanged(key);
} }
} }
public void LoadViewModel()
{
var openFileDialog = new OpenFileDialog {AddExtension = true, DefaultExt = "*.json"};
var result = openFileDialog.ShowDialog(Application.Current.MainWindow?.Owner);
if (result != true) return;
var contents = File.ReadAllText(openFileDialog.FileName);
var obj = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(contents);
foreach (var (key, value) in obj)
{
_valueDict[key] = CastToType(key, value);
OnPropertyChanged(key);
}
}
private object CastToType(string key, JsonElement value)
{
var property = Array.Find(_properties, x => x.Name == key);
if (property.PropertyType == typeof(double))
{
return value.GetDouble();
}
if (property.PropertyType == typeof(bool))
{
return value.GetBoolean();
}
if (property.PropertyType == typeof(int))
{
return value.GetInt32();
}
if (property.PropertyType.IsEnum)
{
return Enum.ToObject(property.PropertyType, value.GetInt32());
}
if (property.PropertyType == typeof(string))
{
return value.GetString();
}
return default;
}
} }
} }

View File

@ -22,6 +22,21 @@
<Window.Resources> <Window.Resources>
<local:PixelsToGridLengthConverter x:Key="PixelsToGridLength" /> <local:PixelsToGridLengthConverter x:Key="PixelsToGridLength" />
</Window.Resources> </Window.Resources>
<Window.InputBindings>
<KeyBinding
Key="O"
Command="{Binding OpenViewModelCommand}"
Modifiers="Control" />
<KeyBinding
Key="S"
Command="{Binding SaveViewModelCommand}"
Modifiers="Control" />
<KeyBinding
Key="N"
Command="{Binding ResetViewModelCommand}"
Modifiers="Control" />
</Window.InputBindings>
<DockPanel> <DockPanel>
<!-- TitleBar --> <!-- TitleBar -->
<Grid <Grid
@ -63,8 +78,18 @@
</Style> </Style>
</Menu.Resources> </Menu.Resources>
<MenuItem Header="File"> <MenuItem Header="File">
<MenuItem Header="New" /> <MenuItem
<MenuItem Header="Open" /> Command="{Binding ResetViewModelCommand}"
Header="New"
InputGestureText="Ctrl+N" />
<MenuItem
Command="{Binding OpenViewModelCommand}"
Header="Open"
InputGestureText="Ctrl+O" />
<MenuItem
Command="{Binding SaveViewModelCommand}"
Header="Save"
InputGestureText="Ctrl+S" />
<Separator /> <Separator />
<MenuItem Command="{Binding CloseCommand}" Header="Close" /> <MenuItem Command="{Binding CloseCommand}" Header="Close" />
</MenuItem> </MenuItem>
@ -172,14 +197,18 @@
Margin="5" Margin="5"
Orientation="Vertical" Orientation="Vertical"
Spacing="5"> Spacing="5">
<Button HorizontalAlignment="Stretch" Content="New" /> <Button
<Button HorizontalAlignment="Stretch" Content="Open" /> HorizontalAlignment="Stretch"
<Separator /> Command="{Binding OpenViewModelCommand}"
<Button HorizontalAlignment="Stretch" Content="Open catalog" /> Content="Open" />
<Button
HorizontalAlignment="Stretch"
Command="{Binding SaveViewModelCommand}"
Content="Save" />
</ui:SimpleStackPanel> </ui:SimpleStackPanel>
</Grid> </Grid>
</TabItem> </TabItem>
<TabItem Header="General"> <TabItem Header="General" IsSelected="True">
<ui:SimpleStackPanel Margin="5" Spacing="10"> <ui:SimpleStackPanel Margin="5" Spacing="10">
<controls:PropertyPresenter2 <controls:PropertyPresenter2
Command="{Binding ShowDialogCommand}" Command="{Binding ShowDialogCommand}"

View File

@ -10,6 +10,9 @@ namespace ModernWpfPlayground
{ {
ShowDialogCommand = new RelayCommand(async x => await ShowDialogAsync()); ShowDialogCommand = new RelayCommand(async x => await ShowDialogAsync());
CloseCommand = new RelayCommand(x => Application.Current.Shutdown()); CloseCommand = new RelayCommand(x => Application.Current.Shutdown());
OpenViewModelCommand = new RelayCommand(x => LoadViewModel());
SaveViewModelCommand = new RelayCommand(x => SaveViewModel());
ResetViewModelCommand = new RelayCommand(x => ResetViewModel());
} }
private async Task ShowDialogAsync() private async Task ShowDialogAsync()
@ -52,5 +55,11 @@ namespace ModernWpfPlayground
} }
public ICommand CloseCommand { get; } public ICommand CloseCommand { get; }
public ICommand OpenViewModelCommand { get; }
public ICommand SaveViewModelCommand { get; }
public ICommand ResetViewModelCommand { get; }
} }
} }