开发者

getting a control from the viewModel

in my viewModel I can get the window associated with it using

var windows = Application.Current.Windows;
            for (var i = 0; i < windows.Count; i++)
            {
                if (windows[i].DataContext == this)
                {
                   //                      
                }开发者_运维问答
            }

there is a FlowDocument in this window that I need a reference to it here in my viewModel, I know I can sometime break the rules and write some code-behind , but since I have the window and this control is contained/child in/of this window I thought I can get it done without aany code-behind , any suggesstions ?

thanks in advance


First of, you're not using MVVM the right way if you need access to UI elements in the ViewModel. You should consider using bindings for this instead (whatever it is that you're doing:-)

Anyway, you can traverse the visual tree to find descendants of the Window. However the FlowDocument isn't in the visual tree as it is a FrameworkContentElement so VisualTreeHelper won't work.

You'll need to combine VisualTreeHelper and LogicalTreeHelper: An implementation of this can be found here: Find Element By Visual Tree

Here is a slightly rewritten version of it, use it like

if (windows[i].DataContext == this)
{
    var flowDocument = windows[i].FindChild<FlowDocument>();
}

DependencyObjectExtensions.cs

public static class DependencyObjectExtensions
{
    public static T FindChild<T>(this DependencyObject source) where T : DependencyObject
    {
        if (source != null)
        {
            var childs = GetChildObjects(source);
            foreach (DependencyObject child in childs)
            {
                //analyze if children match the requested type
                if (child != null && child is T)
                {
                    return (T)child;
                }

                T descendant = FindChild<T>(child);
                if (descendant is T)
                {
                    return descendant;
                }
            }
        }
        return null;
    }
    public static IEnumerable<DependencyObject> GetChildObjects(this DependencyObject parent)
    {
        if (parent == null) yield break;

        if (parent is ContentElement || parent is FrameworkElement)
        {
            //use the logical tree for content / framework elements
            foreach (object obj in LogicalTreeHelper.GetChildren(parent))
            {
                var depObj = obj as DependencyObject;
                if (depObj != null) yield return (DependencyObject)obj;
            }
        }
        else
        {
            //use the visual tree per default
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                yield return VisualTreeHelper.GetChild(parent, i);
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜