alpha
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace InkCanvasForClass.IccInkCanvas.Utils.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// 表示一个可等待对象,如果一个方法返回此类型的实例,则此方法可以使用 `await` 异步等待。
|
||||
/// </summary>
|
||||
/// <typeparam name="TAwaiter">用于给 await 确定返回时机的 IAwaiter 的实例。</typeparam>
|
||||
public interface IAwaitable<out TAwaiter> where TAwaiter : IAwaiter
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取一个可用于 await 关键字异步等待的异步等待对象。
|
||||
/// 此方法会被编译器自动调用。
|
||||
/// </summary>
|
||||
TAwaiter GetAwaiter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表示一个包含返回值的可等待对象,如果一个方法返回此类型的实例,则此方法可以使用 `await` 异步等待返回值。
|
||||
/// </summary>
|
||||
/// <typeparam name="TAwaiter">用于给 await 确定返回时机的 IAwaiter{<typeparamref name="TResult"/>} 的实例。</typeparam>
|
||||
/// <typeparam name="TResult">异步返回的返回值类型。</typeparam>
|
||||
public interface IAwaitable<out TAwaiter, out TResult> where TAwaiter : IAwaiter<TResult>
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取一个可用于 await 关键字异步等待的异步等待对象。
|
||||
/// 此方法会被编译器自动调用。
|
||||
/// </summary>
|
||||
TAwaiter GetAwaiter();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用于给 await 确定异步返回的时机。
|
||||
/// </summary>
|
||||
public interface IAwaiter : INotifyCompletion
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取一个状态,该状态表示正在异步等待的操作已经完成(成功完成或发生了异常);此状态会被编译器自动调用。
|
||||
/// 在实现中,为了达到各种效果,可以灵活应用其值:可以始终为 true,或者始终为 false。
|
||||
/// </summary>
|
||||
bool IsCompleted { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 此方法会被编译器在 await 结束时自动调用以获取返回状态(包括异常)。
|
||||
/// </summary>
|
||||
void GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当执行关键代码(此代码中的错误可能给应用程序中的其他状态造成负面影响)时,
|
||||
/// 用于给 await 确定异步返回的时机。
|
||||
/// </summary>
|
||||
public interface ICriticalAwaiter : IAwaiter, ICriticalNotifyCompletion
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用于给 await 确定异步返回的时机,并获取到返回值。
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">异步返回的返回值类型。</typeparam>
|
||||
public interface IAwaiter<out TResult> : INotifyCompletion
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取一个状态,该状态表示正在异步等待的操作已经完成(成功完成或发生了异常);此状态会被编译器自动调用。
|
||||
/// 在实现中,为了达到各种效果,可以灵活应用其值:可以始终为 true,或者始终为 false。
|
||||
/// </summary>
|
||||
bool IsCompleted { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取此异步等待操作的返回值,此方法会被编译器在 await 结束时自动调用以获取返回值(包括异常)。
|
||||
/// </summary>
|
||||
/// <returns>异步操作的返回值。</returns>
|
||||
TResult GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当执行关键代码(此代码中的错误可能给应用程序中的其他状态造成负面影响)时,
|
||||
/// 用于给 await 确定异步返回的时机,并获取到返回值。
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">异步返回的返回值类型。</typeparam>
|
||||
public interface ICriticalAwaiter<out TResult> : IAwaiter<TResult>, ICriticalNotifyCompletion
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
|
||||
using System;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Windows.Threading;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace InkCanvasForClass.IccInkCanvas.Utils.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// 表示可以等待一个主要运行在 UI 线程的异步操作。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">异步等待 UI 操作结束后的返回值类型。</typeparam>
|
||||
public class DispatcherAsyncOperation<T> : DispatcherObject,
|
||||
IAwaitable<DispatcherAsyncOperation<T>, T>, IAwaiter<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建 <see cref="DispatcherAsyncOperation{T}"/> 的新实例。
|
||||
/// </summary>
|
||||
private DispatcherAsyncOperation()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个可用于 await 关键字异步等待的异步等待对象。
|
||||
/// 此方法会被编译器自动调用。
|
||||
/// </summary>
|
||||
/// <returns>返回自身,用于异步等待返回值。</returns>
|
||||
public DispatcherAsyncOperation<T> GetAwaiter()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个状态,该状态表示正在异步等待的操作已经完成(成功完成或发生了异常)。
|
||||
/// 此状态会被编译器自动调用。
|
||||
/// </summary>
|
||||
public bool IsCompleted { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取此异步等待操作的返回值。
|
||||
/// 与 <see cref="System.Threading.Tasks.Task{TResult}"/> 不同的是,
|
||||
/// 如果操作没有完成或发生了异常,此实例会返回 <typeparamref name="T"/> 的默认值,
|
||||
/// 而不是阻塞线程直至任务完成。
|
||||
/// </summary>
|
||||
public T Result { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取此异步等待操作的返回值,此方法会被编译器在 await 结束时自动调用以获取返回值。
|
||||
/// 与 <see cref="System.Threading.Tasks.Task{TResult}"/> 不同的是,
|
||||
/// 如果操作没有完成,此实例会返回 <typeparamref name="T"/> 的默认值,而不是阻塞线程直至任务完成。
|
||||
/// 但是,如果异步操作中发生了异常,调用此方法会抛出这个异常。
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// 异步操作的返回值。
|
||||
/// </returns>
|
||||
public T GetResult()
|
||||
{
|
||||
if (_exception != null)
|
||||
{
|
||||
ExceptionDispatchInfo.Capture(_exception).Throw();
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用 Builder 模式配置此异步操作执行完后,后续任务执行采用的优先级。
|
||||
/// 不配置时,使用的是 <see cref="DispatcherPriority.Normal"/>。
|
||||
/// </summary>
|
||||
/// <param name="priority">使用 <see cref="Dispatcher"/> 调度的后续任务的优先级。</param>
|
||||
/// <returns>实例自身。</returns>
|
||||
public DispatcherAsyncOperation<T> ConfigurePriority(DispatcherPriority priority)
|
||||
{
|
||||
_priority = priority;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当使用此类型执行异步任务的方法执行完毕后,编译器会自动调用此方法。
|
||||
/// 也就是说,此方法会在调用方所在的线程执行,用于通知调用方所在线程的代码已经执行完毕,请求执行 await 后续任务。
|
||||
/// 在此类型中,后续任务是通过 <see cref="Dispatcher.InvokeAsync(Action, DispatcherPriority)"/> 来执行的。
|
||||
/// </summary>
|
||||
/// <param name="continuation">
|
||||
/// 被异步任务状态机包装的后续任务。当执行时,会让状态机继续往下走一步。
|
||||
/// </param>
|
||||
public void OnCompleted(Action continuation)
|
||||
{
|
||||
if (IsCompleted)
|
||||
{
|
||||
// 如果 await 开始时任务已经执行完成,则直接执行 await 后面的代码。
|
||||
// 注意,即便 _continuation 有值,也无需关心,因为报告结束的时候就会将其执行。
|
||||
continuation?.Invoke();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 当使用多个 await 关键字等待此同一个 awaitable 实例时,此 OnCompleted 方法会被多次执行。
|
||||
// 当任务真正结束后,需要将这些所有的 await 后面的代码都执行。
|
||||
_continuation += continuation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 调用此方法以报告任务结束,并指定返回值和异步任务中的异常。
|
||||
/// 当使用 <see cref="Create"/> 静态方法创建此类型的实例后,调用方可以通过方法参数中传出的委托来调用此方法。
|
||||
/// </summary>
|
||||
/// <param name="result">异步返回值。</param>
|
||||
/// <param name="exception">异步操作中的异常。</param>
|
||||
private void ReportResult(T result, Exception exception)
|
||||
{
|
||||
Result = result;
|
||||
_exception = exception;
|
||||
IsCompleted = true;
|
||||
|
||||
// _continuation 可能为 null,说明任务已经执行完毕,但没有任何一处 await 了这个任务。
|
||||
if (_continuation != null)
|
||||
{
|
||||
// 无论此方法执行时所在线程关联的 Dispatcher 是否等于此类型创建时的 Dispatcher;
|
||||
// 都 Invoke 到创建时的 Dispatcher 上,以便对当前执行上下文造成影响在不同线程执行下都一致(如异常)。
|
||||
Dispatcher.InvokeAsync(_continuation, _priority);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 临时保存 await 后后续任务的包装,用于报告任务完成后能够继续执行。
|
||||
/// </summary>
|
||||
private Action _continuation;
|
||||
|
||||
/// <summary>
|
||||
/// 临时保存异步任务执行过程中发生的异常。它会在异步等待结束后抛出,以报告异步执行过程中发生的错误。
|
||||
/// </summary>
|
||||
private Exception _exception;
|
||||
|
||||
/// <summary>
|
||||
/// 储存恢复 await 后续任务时需要使用的优先级。
|
||||
/// </summary>
|
||||
private DispatcherPriority _priority = DispatcherPriority.Normal;
|
||||
|
||||
/// <summary>
|
||||
/// 创建 <see cref="DispatcherAsyncOperation{T}"/> 的新实例,并得到一个可以用于报告操作执行完毕的委托。
|
||||
/// </summary>
|
||||
/// <param name="reportResult">一个委托。调用此委托可以报告任务已经执行完毕,并给定返回值和异常信息。</param>
|
||||
/// <returns>
|
||||
/// 创建好的 <see cref="DispatcherAsyncOperation{T}"/> 的新实例,将此返回值作为方法的返回值可以让方法支持 await 异步等待。
|
||||
/// </returns>
|
||||
public static DispatcherAsyncOperation<T> Create([NotNull] out Action<T, Exception> reportResult)
|
||||
{
|
||||
var asyncOperation = new DispatcherAsyncOperation<T>();
|
||||
reportResult = asyncOperation.ReportResult;
|
||||
return asyncOperation;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
using JetBrains.Annotations;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Markup;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace InkCanvasForClass.IccInkCanvas.Utils.Threading
|
||||
{
|
||||
[ContentProperty(nameof(Child))]
|
||||
public sealed class DispatcherContainer : FrameworkElement
|
||||
{
|
||||
public DispatcherContainer()
|
||||
{
|
||||
_hostVisual = new InteractiveHostVisual();
|
||||
}
|
||||
|
||||
private readonly HostVisual _hostVisual;
|
||||
private VisualTargetPresentationSource _targetSource;
|
||||
|
||||
#region Child
|
||||
|
||||
private bool _isUpdatingChild;
|
||||
[CanBeNull] private UIElement _child;
|
||||
public UIElement Child => _child;
|
||||
|
||||
public async Task SetChildAsync<T>([CanBeNull] Dispatcher dispatcher = null)
|
||||
where T : UIElement, new()
|
||||
{
|
||||
await SetChildAsync(() => new T(), dispatcher);
|
||||
}
|
||||
|
||||
public async Task SetChildAsync<T>(Func<T> @new, [CanBeNull] Dispatcher dispatcher = null)
|
||||
where T : UIElement
|
||||
{
|
||||
dispatcher = dispatcher ?? await UIDispatcher.RunNewAsync($"{typeof(T).Name}");
|
||||
var child = await dispatcher.InvokeAsync(@new);
|
||||
await SetChildAsync(child);
|
||||
}
|
||||
|
||||
public async Task SetChildAsync(UIElement value)
|
||||
{
|
||||
if (_isUpdatingChild)
|
||||
{
|
||||
throw new InvalidOperationException("Child property should not be set during Child updating.");
|
||||
}
|
||||
|
||||
_isUpdatingChild = true;
|
||||
try
|
||||
{
|
||||
await SetChildAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isUpdatingChild = false;
|
||||
}
|
||||
|
||||
async Task SetChildAsync()
|
||||
{
|
||||
var oldChild = _child;
|
||||
var visualTarget = _targetSource;
|
||||
|
||||
if (Equals(oldChild, value))
|
||||
return;
|
||||
|
||||
_targetSource = null;
|
||||
if (visualTarget != null)
|
||||
{
|
||||
RemoveVisualChild(oldChild);
|
||||
await visualTarget.Dispatcher.InvokeAsync(visualTarget.Dispose);
|
||||
}
|
||||
|
||||
_child = value;
|
||||
|
||||
if (value == null)
|
||||
{
|
||||
_targetSource = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
await value.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
_targetSource = new VisualTargetPresentationSource(_hostVisual)
|
||||
{
|
||||
RootVisual = value,
|
||||
};
|
||||
});
|
||||
AddVisualChild(_hostVisual);
|
||||
}
|
||||
InvalidateMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Tree & Layout
|
||||
|
||||
protected override Visual GetVisualChild(int index)
|
||||
{
|
||||
if (index != 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(index));
|
||||
return _hostVisual;
|
||||
}
|
||||
|
||||
protected override int VisualChildrenCount => _child != null ? 1 : 0;
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize)
|
||||
{
|
||||
var child = _child;
|
||||
if (child == null)
|
||||
return default(Size);
|
||||
|
||||
child.Dispatcher.InvokeAsync(
|
||||
() => child.Measure(availableSize),
|
||||
DispatcherPriority.Loaded);
|
||||
|
||||
return default(Size);
|
||||
}
|
||||
|
||||
protected override Size ArrangeOverride(Size finalSize)
|
||||
{
|
||||
var child = _child;
|
||||
if (child == null)
|
||||
return finalSize;
|
||||
|
||||
child.Dispatcher.InvokeAsync(
|
||||
() => child.Arrange(new Rect(finalSize)),
|
||||
DispatcherPriority.Loaded);
|
||||
|
||||
return finalSize;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region HitTest
|
||||
|
||||
protected override HitTestResult HitTestCore(PointHitTestParameters htp)
|
||||
{
|
||||
var child = _child;
|
||||
|
||||
var element = child?.Dispatcher.Invoke(() =>
|
||||
{
|
||||
double offsetX = 0d, offsetY = 0d;
|
||||
if (child is FrameworkElement fe)
|
||||
{
|
||||
offsetX = fe.Margin.Left;
|
||||
offsetY = fe.Margin.Top;
|
||||
}
|
||||
return _child.InputHitTest(new Point(htp.HitPoint.X - offsetX, htp.HitPoint.Y - offsetY));
|
||||
}, DispatcherPriority.Normal);
|
||||
if (element == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new PointHitTestResult(this, htp.HitPoint);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace InkCanvasForClass.IccInkCanvas.Utils.Threading
|
||||
{
|
||||
public class InteractiveHostVisual : HostVisual
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Threading;
|
||||
using System.Windows.Threading;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace InkCanvasForClass.IccInkCanvas.Utils.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// 包含扩展 <see cref="Dispatcher"/> 的一些方法。
|
||||
/// </summary>
|
||||
public static class UIDispatcher
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建一个可以运行 <see cref="Dispatcher"/> 的后台 UI 线程,并返回这个线程的调度器 <see cref="Dispatcher"/>。
|
||||
/// </summary>
|
||||
/// <param name="name">线程的名称,如果不指定,将使用 “BackgroundUI”。</param>
|
||||
/// <returns>一个可以异步等待的 <see cref="Dispatcher"/>。</returns>
|
||||
public static DispatcherAsyncOperation<Dispatcher> RunNewAsync([CanBeNull] string name = null)
|
||||
{
|
||||
// 创建一个可等待的异步操作。
|
||||
var awaiter = DispatcherAsyncOperation<Dispatcher>.Create(out var reportResult);
|
||||
|
||||
// 记录原线程关联的 Dispatcher,以便在意外时报告异常。
|
||||
var originDispatcher = Dispatcher.CurrentDispatcher;
|
||||
|
||||
// 创建后台线程。
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// 获取关联此后台线程的 Dispatcher。
|
||||
var dispatcher = Dispatcher.CurrentDispatcher;
|
||||
|
||||
// 设置此线程的 SynchronizationContext,以便此线程上 await 之后能够返回此线程。
|
||||
SynchronizationContext.SetSynchronizationContext(
|
||||
new DispatcherSynchronizationContext(dispatcher));
|
||||
|
||||
// 报告 Dispatcher 已创建完毕,使用 await 异步等待 Dispatcher 创建的地方可以继续执行了。
|
||||
reportResult(dispatcher, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 报告创建过程中发生的异常。
|
||||
// 不需要担心其内部发生的异常,因为会被异步状态机捕获后重新在原线程上抛出。
|
||||
reportResult(null, ex);
|
||||
}
|
||||
|
||||
// 此线程的以下代码将脱离异步状态机的控制,需要自己处理异常。
|
||||
try
|
||||
{
|
||||
// 启动 Dispatcher,开始此线程上消息的调度。
|
||||
Dispatcher.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 如果新的 Dispatcher 线程上出现了未处理的异常,则将其抛到原调用线程上。
|
||||
originDispatcher.InvokeAsync(() => ExceptionDispatchInfo.Capture(ex).Throw());
|
||||
}
|
||||
})
|
||||
{
|
||||
Name = name ?? "BackgroundUI",
|
||||
IsBackground = true,
|
||||
};
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
return awaiter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建一个可以运行 <see cref="Dispatcher"/> 的后台 UI 线程,并返回这个线程的调度器 <see cref="Dispatcher"/>。
|
||||
/// </summary>
|
||||
/// <param name="name">线程的名称,如果不指定,将使用 “BackgroundUI”。</param>
|
||||
/// <returns>后台线程创建并启动的 <see cref="Dispatcher"/>。</returns>
|
||||
public static Dispatcher RunNew([CanBeNull] string name = null)
|
||||
{
|
||||
var resetEvent = new AutoResetEvent(false);
|
||||
|
||||
// 记录原线程关联的 Dispatcher,以便在意外时报告异常。
|
||||
var originDispatcher = Dispatcher.CurrentDispatcher;
|
||||
Exception innerException = null;
|
||||
Dispatcher dispatcher = null;
|
||||
|
||||
// 创建后台线程。
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// 获取关联此后台线程的 Dispatcher。
|
||||
dispatcher = Dispatcher.CurrentDispatcher;
|
||||
|
||||
// 设置此线程的 SynchronizationContext,以便此线程上 await 之后能够返回此线程。
|
||||
SynchronizationContext.SetSynchronizationContext(
|
||||
new DispatcherSynchronizationContext(dispatcher));
|
||||
|
||||
// 报告 Dispatcher 已创建完毕,使用 ResetEvent 同步等待 Dispatcher 创建的地方可以继续执行了。
|
||||
resetEvent.Set();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 报告创建过程中发生的异常。
|
||||
innerException = ex;
|
||||
resetEvent.Set();
|
||||
}
|
||||
|
||||
// 此线程的以下代码将脱离异步状态机的控制,需要自己处理异常。
|
||||
try
|
||||
{
|
||||
// 启动 Dispatcher,开始此线程上消息的调度。
|
||||
Dispatcher.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 如果新的 Dispatcher 线程上出现了未处理的异常,则将其抛到原调用线程上。
|
||||
originDispatcher.InvokeAsync(() => ExceptionDispatchInfo.Capture(ex).Throw());
|
||||
}
|
||||
})
|
||||
{
|
||||
Name = name ?? "BackgroundUI",
|
||||
IsBackground = true,
|
||||
};
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
resetEvent.WaitOne();
|
||||
resetEvent.Dispose();
|
||||
resetEvent = null;
|
||||
if (innerException != null)
|
||||
{
|
||||
ExceptionDispatchInfo.Capture(innerException).Throw();
|
||||
}
|
||||
return dispatcher;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace InkCanvasForClass.IccInkCanvas.Utils.Threading
|
||||
{
|
||||
/// <summary>
|
||||
/// The VisualTargetPresentationSource represents the root
|
||||
/// of a visual subtree owned by a different thread that the
|
||||
/// visual tree in which is is displayed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A HostVisual belongs to the same UI thread that owns the
|
||||
/// visual tree in which it resides.
|
||||
///
|
||||
/// A HostVisual can reference a VisualTarget owned by another
|
||||
/// thread.
|
||||
///
|
||||
/// A VisualTarget has a root visual.
|
||||
///
|
||||
/// VisualTargetPresentationSource wraps the VisualTarget and
|
||||
/// enables basic functionality like Loaded, which depends on
|
||||
/// a PresentationSource being available.
|
||||
/// </remarks>
|
||||
public class VisualTargetPresentationSource : PresentationSource, IDisposable
|
||||
{
|
||||
public VisualTargetPresentationSource(HostVisual hostVisual)
|
||||
{
|
||||
_visualTarget = new VisualTarget(hostVisual);
|
||||
}
|
||||
|
||||
public override Visual RootVisual
|
||||
{
|
||||
get => _visualTarget.RootVisual;
|
||||
set
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
throw new ObjectDisposedException("VisualTarget");
|
||||
}
|
||||
|
||||
var oldRoot = _visualTarget.RootVisual;
|
||||
|
||||
// Set the root visual of the VisualTarget. This visual will
|
||||
// now be used to visually compose the scene.
|
||||
_visualTarget.RootVisual = value;
|
||||
|
||||
// Hook the SizeChanged event on framework elements for all
|
||||
// future changed to the layout size of our root, and manually
|
||||
// trigger a size change.
|
||||
if (oldRoot is FrameworkElement oldRootFe)
|
||||
{
|
||||
oldRootFe.SizeChanged -= root_SizeChanged;
|
||||
}
|
||||
if (value is FrameworkElement rootFe)
|
||||
{
|
||||
rootFe.SizeChanged += root_SizeChanged;
|
||||
rootFe.DataContext = _dataContext;
|
||||
|
||||
if (_propertyName != null)
|
||||
{
|
||||
var myBinding = new Binding(_propertyName)
|
||||
{
|
||||
Source = _dataContext
|
||||
};
|
||||
rootFe.SetBinding(TextBlock.TextProperty, myBinding);
|
||||
}
|
||||
}
|
||||
|
||||
// Tell the PresentationSource that the root visual has
|
||||
// changed. This kicks off a bunch of stuff like the
|
||||
// Loaded event.
|
||||
RootChanged(oldRoot, value);
|
||||
|
||||
// Kickoff layout...
|
||||
if (value is UIElement rootElement)
|
||||
{
|
||||
rootElement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
|
||||
rootElement.Arrange(new Rect(rootElement.DesiredSize));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public object DataContext
|
||||
{
|
||||
get => _dataContext;
|
||||
set
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
throw new ObjectDisposedException("VisualTarget");
|
||||
}
|
||||
|
||||
if (_dataContext == value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_dataContext = value;
|
||||
if (_visualTarget.RootVisual is FrameworkElement rootElement)
|
||||
{
|
||||
rootElement.DataContext = _dataContext;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string PropertyName
|
||||
{
|
||||
get => _propertyName;
|
||||
set
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
throw new ObjectDisposedException("VisualTarget");
|
||||
}
|
||||
|
||||
_propertyName = value;
|
||||
|
||||
if (_visualTarget.RootVisual is TextBlock rootElement)
|
||||
{
|
||||
if (!rootElement.CheckAccess())
|
||||
{
|
||||
throw new InvalidOperationException("What?");
|
||||
}
|
||||
|
||||
var myBinding = new Binding(_propertyName)
|
||||
{
|
||||
Source = _dataContext
|
||||
};
|
||||
rootElement.SetBinding(TextBlock.TextProperty, myBinding);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event SizeChangedEventHandler SizeChanged;
|
||||
|
||||
public override bool IsDisposed => _isDisposed;
|
||||
|
||||
protected override CompositionTarget GetCompositionTargetCore()
|
||||
{
|
||||
return _visualTarget;
|
||||
}
|
||||
|
||||
private void root_SizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SizeChanged?.Invoke(this, e);
|
||||
}
|
||||
|
||||
private readonly VisualTarget _visualTarget;
|
||||
private object _dataContext;
|
||||
private string _propertyName;
|
||||
private bool _isDisposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_visualTarget?.Dispose();
|
||||
_isDisposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user