首页 > 解决方案 > 如何在 WPF 中捕获 DataTemplate 的实例化?

问题描述

我有一个搜索窗口,如下所示:

搜索窗口

带有 Condition 和 Options 的部分是一个ContentControl带有多个DataTemplates 的部分,其中包含针对特定字段的不同过滤形式(例如 datetime 选择器等)。

我希望DataTemplate在打开窗口后关注特定控件(如果有人问,这是 X 问题)

我这样做是通过以下方式:

    public FindWindow(FindModel model)
    {
        InitializeComponent();

        this.viewModel = Dependencies.Container.Instance.Resolve<FindWindowViewModel>(new ParameterOverride("access", this), new ParameterOverride("model", model));
        DataContext = viewModel;
        FocusInput();
    }

FocusInput 执行以下操作:

    public static FrameworkElement GetControlByName(DependencyObject parent, string name)
    {
        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; i < count; ++i)
        {
            var child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
            if (child != null)
            {
                if (child.Name == name)
                {
                    return child;
                }
                var descendantFromName = GetControlByName(child, name);
                if (descendantFromName != null)
                {
                    return descendantFromName;
                }
            }
        }
        return null;
    }

    public void FocusInput()
    {
        Dispatcher.Invoke(DispatcherPriority.ContextIdle, new Action(() =>
        {
            var obj = GetControlByName(filterContainer, "input");
            if (obj != null && obj is Control ctl)
                ctl.Focus();
        }));            
    }

当它在 ctor 中运行时,FindWindow得到 null obj(尽管ContentControlContent设置)。但是,当您单击“测试”按钮时,它只是运行FocusControl,后者又会找到所需的控件并将其聚焦。

问题是:如何在ContentControl完成实例化时捕获时刻,DataTemplate以便我可以捕获所需的控制?(问题 Y)

我将感谢解决问题 X 或 Y(这是我尝试的解决方案)。

标签: c#wpfbinding

解决方案


尝试FocusInput()在窗口或ContentControl已加载后调用:

public FindWindow(FindModel model)
{
    InitializeComponent();

    this.viewModel = Dependencies.Container.Instance.Resolve<FindWindowViewModel>(new ParameterOverride("access", this), new ParameterOverride("model", model));
    DataContext = viewModel;
    Loaded += (s, e) => FocusInput();
}

推荐阅读