Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture instantiation of DataTemplate in WPF?

Tags:

c#

binding

wpf

I have a search window, which looks like following:

Search window

The part with Condition and Options is a ContentControl with several DataTemplates, which contain different filter form for specific field (eg. datetime picker etc.).

I'd like specific control in the DataTemplate to be focused after opening the window (this is the X problem if someone asked)

I'm doing that in the following way:

    public FindWindow(FindModel model)
    {
        InitializeComponent();

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

FocusInput does the following:

    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();
        }));            
    }

When it runs in the ctor, FindWindow gets null obj (despite ContentControl having Content set). However, when you click "Test" button, which simply runs FocusControl, the latter in turn finds required control and focuses it.

The question is: how to capture moment, when ContentControl finishes instantiating DataTemplate, such that I can capture required control? (Problem Y)

I'll be grateful for solution to either problem X or Y (which is my attempted solution).

like image 822
Spook Avatar asked Dec 06 '25 05:12

Spook


1 Answers

Try to call FocusInput() once the window or ContentControl has been loaded:

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();
}
like image 51
mm8 Avatar answered Dec 09 '25 02:12

mm8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!