如何通过viewmodel找到view?
之前的做法是,在view加载时(Loaded),将view保存到viewmodel中,后来想想Caliburn-Micro,自带方法可以通过viewmodel找到view,但是在网上搜索一番,无果。但是后来仔细想想,除非在viewmodel和view之间建立关系,否则是是找不到的。大部分viewmodel是作为对应的view的datacontext。要找到view,难道遍历可视化树,比对datacontex?显然是不行的,wpf不提供,Caliburn-Micro是否在绑定viewmodel是否做了手脚?看到以下的代码:
public static Action<object, DependencyObject, object> Bind = (viewModel, view, context) => {
if ((bool)view.GetValue(noContext)) {
Action.SetTargetWithoutContext(view, viewModel);
}
else {
Action.SetTarget(view, viewModel);
}
var viewAware = viewModel as IViewAware;
if (viewAware != null) {
Log.Info("Attaching {0} to {1}.", view, viewAware);
viewAware.AttachView(view, context);
}
if ((bool)view.GetValue(ConventionsAppliedProperty)) {
return;
}
var element = View.GetFirstNonGeneratedView(view) as FrameworkElement;
if (element == null) {
return;
};
___var viewAware = viewModel as IViewAware;
if (viewAware != null) {
Log.Info("Attaching {0} to {1}.", view, viewAware);
viewAware.AttachView(view, context);
}
namespace Caliburn.Micro {
using System;
/// <summary>
/// Denotes a class which is aware of its view(s).
/// </summary>
public interface IViewAware {
/// <summary>
/// Attaches a view to this instance.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="context">The context in which the view appears.</param>
void AttachView(object view, object context = null);
/// <summary>
/// Gets a view previously attached to this instance.
/// </summary>
/// <param name="context">The context denoting which view to retrieve.</param>
/// <returns>The view.</returns>
object GetView(object context = null);
/// <summary>
/// Raised when a view is attached.
/// </summary>
event EventHandler<ViewAttachedEventArgs> ViewAttached;
}
}
所以只要viewmodel实现IViewAware接口就可以。