c# - 如何在 WPF 中捕获 DataTemplate 的实例化?
问题描述
我有一个搜索窗口,如下所示:
带有 Condition 和 Options 的部分是一个ContentControl
带有多个DataTemplate
s 的部分,其中包含针对特定字段的不同过滤形式(例如 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(尽管ContentControl
已Content
设置)。但是,当您单击“测试”按钮时,它只是运行FocusControl
,后者又会找到所需的控件并将其聚焦。
问题是:如何在ContentControl
完成实例化时捕获时刻,DataTemplate
以便我可以捕获所需的控制?(问题 Y)
我将感谢解决问题 X 或 Y(这是我尝试的解决方案)。
解决方案
尝试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();
}
推荐阅读
- amazon-web-services - AWS - 摆脱 Elastic Load Balancing
- python - TkDnD 错误:无法加载 tkdnd 库(_tkinter.TclError:找不到包 tkdnd)
- java - GRPC 连接状态何时发生变化?
- android - 'boolean java.io.File.exists()' 中的 java.lang.NullPointerException
- node.js - 在 Strapi 中更改 Google 提供商的重定向网址
- curl - 从管道向 gitlab-ci 合并请求发送消息
- python - Python:如何获取知道文件夹名称的文件夹的路径?
- android - 是否可以将初始文本添加到通知 RemoteInput(Android)?
- php - PHP Curl 未设置正文参数或内容类型
- swift - 搜索乱序条款