以下代码位于视图模型中:
我正在使用 FormattedText 创建一个显示列表。在离开创建格式化文本的方法之前(即,在方法完成时的正常渲染机制之前),我需要获得显示内容的最终指标。我一直在使用调度程序尝试这些方面的东西,但似乎无法获得最终的计量标准。无论我如何设置调度程序或如何调用它,StringViewModel 的实际格式化文本 ft 始终为空。我正在收集该操作是在调度程序进行渲染之前执行的。(净 4.0)
Action<StringViewModel> action = delegate(StringViewModel sv)
{
// do stuff to UI, e.g.
var Height = sv.ft.Height;
};
svm.Dispatcher.BeginInvoke(DispatcherPriority.Render, action, svm);
请提供任何帮助。如何才能做到这一点?任何想法都会很棒!
字符串视图模型:
public class StringViewModel : FrameworkElement
{
public StringViewModel(
Point topleft,
string text,
double fontsizediu,
SolidColorBrush brush,
Func<FormattedText,FormattedText> f,
double lineheight)
{
this.text = text;
this.emSize = fontsizediu;
this.color = brush;
this.topleft = topleft;
this.lineheight = lineheight;
this.f = f;
}
protected override void OnRender(DrawingContext dc)
{
ft = new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(new FontFamily("Segoe Script"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal),
emSize,
color);
ft.TextAlignment = TextAlignment.Left;
if (lineheight == null)
ft.LineHeight = 1.25 * FontSize;
ft = f(ft);
dc.DrawText(ft, topleft);
}
编辑:
以上所有代码都在 View Model 中,而不是后面的代码,如果我将其更改为
StringViewModel svm = new StringViewModel(p, r, FontSizeDIU, b, stringstyle, LineHeight);
Strings.Add(svm);
this.theView.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state)
{
var size = svm.DesiredSize;
return null;
}
), null);
其中 ObservableCollection Strings 和 theView 是对视图的引用,所有工作都正确。
那么,不让视图模型“知道”视图但使用视图的调度程序来测量渲染文本的推荐方法是什么?