Caliburn Micro:如何将文本添加到列表框的底部并显示它

时间:2012-11-04 21:57:29

标签: caliburn.micro

我正在试图弄清楚如何将文本添加到列表框的底部并显示它。在代码落后的WPF中,我会抓住ScrollViewer并对其进行操作,但我无法弄清楚如何使用Caliburn ...

1 个答案:

答案 0 :(得分:1)

你有两个选择。

1)在ViewModel中,您可以调用GetView并将其转换为您的视图类型,并获取对ScrollViewer的引用。类似的东西:

var myView = this.GetView() as MyView;
var myScrollView = myView.MyScrollView;

这样可以正常工作,但如果您不想将视图耦合到视图模型,则效果不理想。

选项2)是实现IResult,请参阅文档here

public class ScrollViewResult : IResult
    {
        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };

        private ScrollViewResult ()
        {
        }

        public void Execute (ActionExecutionContext context)
        {
            var view = context.View as FrameworkElement;
            var scrollViewer = FindVisualChild<ScrollViewer>(view);

            //do stuff to scrollViewer here

            Completed (this, new ResultCompletionEventArgs { });
        }

        private static TChildItem FindVisualChild<TChildItem> (DependencyObject obj)
            where TChildItem : DependencyObject
        {
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount (obj); i++)
            {
                var child = VisualTreeHelper.GetChild (obj, i);
                if (child != null && child is TChildItem)
                    return (TChildItem)child;

                var childOfChild = FindVisualChild<TChildItem> (child);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }

        //this isn't required of course but comes in handy for 
        //having a static method and passing parameters to the
        //ctor of the IResult
        public static IResult DoSomething ()
        {
            return new ScrollViewResult ();
        }

然后你可以这样称呼它:

public IEnumerable<IResult> SomeAction()
        {
            yield return ScrollViewResult.DoSomething();
        }