CPF/CPF.Toolkit/ViewBehavior.cs

92 lines
2.6 KiB
C#
Raw Permalink Normal View History

2024-01-25 22:35:00 +08:00
using CPF.Controls;
using System;
using System.Collections.Generic;
using System.Text;
namespace CPF.Toolkit
{
public class ViewBehavior : Behavior<Window>
{
protected override void OnBehaviorTo(Window window)
{
2024-01-25 23:31:09 +08:00
this.DataContextChanged(window);
2024-01-25 22:35:00 +08:00
window.PropertyChanged += Window_PropertyChanged;
window.Loaded += Window_Loaded;
window.Closing += Window_Closing;
window.Closed += Window_Closed;
base.OnBehaviorTo(window);
}
protected override void OnDetachingFrom(Window window)
{
window.PropertyChanged -= Window_PropertyChanged;
window.Loaded -= Window_Loaded;
window.Closing -= Window_Closing;
window.Closed -= Window_Closed;
base.OnDetachingFrom(window);
}
private void Window_Closed(object sender, EventArgs e)
{
var window = (Window)sender;
if (window.DataContext is IDisposable disposable)
{
disposable.Dispose();
}
}
private void Window_Closing(object sender, ClosingEventArgs e)
{
var window = (Window)sender;
if (window.DataContext is ICloseable closeable)
{
closeable.OnClosable(e);
}
}
private void Window_Loaded(object sender, EventArgs e)
{
var window = (Window)sender;
if (window.DataContext is ILoaded loaded)
{
loaded.OnLoaded();
}
}
2024-01-25 23:31:09 +08:00
void DataContextChanged(Window window)
2024-01-25 22:35:00 +08:00
{
2024-01-25 23:31:09 +08:00
if (window == null) throw new ArgumentNullException(nameof(window));
if (window.DataContext is ICloseable closeable)
2024-01-25 22:35:00 +08:00
{
2024-01-25 23:31:09 +08:00
closeable.Closable -= Closeable_Closable;
closeable.Closable += Closeable_Closable;
}
if (window.DataContext is IDialog dialog)
{
dialog.Dialog = new DialogService(window);
2024-01-25 22:35:00 +08:00
}
void Closeable_Closable(object _, ClosingEventArgs ee)
{
if (!ee.Cancel)
{
window.Close();
}
}
}
2024-01-25 23:31:09 +08:00
private void Window_PropertyChanged(object sender, CPFPropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(DataContext):
{
DataContextChanged(sender as Window);
}
break;
}
}
2024-01-25 22:35:00 +08:00
}
}