c# - 用于输入的 C# WPF 动态名称
问题描述
因此,我尝试动态添加输入并从中检索日期,并且仅在用户在输入中按 Enter 时执行操作。所以,我目前正在做的是将输入附加到堆栈布局。效果很好。命名也有效。我使用以下功能;
private void GenerateGTKInputs()
{
// Based on the settings for the tour
// we generate the correct inputs in the stacklayout given in the XAML
// First: clear all the children
stackpanel_gtk.Children.Clear();
if (inp_team_number.Text != "")
{
// get the data for the part and the class etc...
var data_gtk = tour_settings[(Convert.ToInt32(inp_team_number.Text.Substring(0, 1)) - 1)].tour_data[inp_tour_part.SelectedIndex].gtks;
// Now: Make the layout
foreach (var item in data_gtk)
{
// Stack panel (main 'div')
StackPanel main_stack_panel = new StackPanel()
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Left
};
// Text blok with the name of the GTK
TextBlock gtk_name = new TextBlock()
{
FontWeight = FontWeights.Bold,
Text = "GTK " + item.gtk
};
// Input field
Xceed.Wpf.Toolkit.MaskedTextBox input = new Xceed.Wpf.Toolkit.MaskedTextBox()
{
Margin = new Thickness(15, 0, 0, 0),
Width = 40,
Height = Double.NaN, // Automatic height
TextAlignment = TextAlignment.Center,
Mask = "00:00",
Name = "gtk_" + item.gtk
};
// Add to the main stack panel
main_stack_panel.Children.Add(gtk_name);
main_stack_panel.Children.Add(input);
// Append to the main main frame
stackpanel_gtk.Children.Add(main_stack_panel);
}
}
}
现在如您所见,我给它们起了一个名字,但我不知道如何KeyDown
通过检查输入按钮按下动态名称来“绑定”触发事件()。有人可以帮我吗?
解决方案
您通过添加到控件的适当事件来“绑定”触发事件 - 在这种情况下,您需要创建一个方法,例如:
private void OnKeyDown(object sender, System.Windows.Input.KeyEventArgs keyEventArgs)
{
// Get reference to the input control that fired the event
Xceed.Wpf.Toolkit.MaskedTextBox input = (Xceed.Wpf.Toolkit.MaskedTextBox)sender;
// input.Name can now be used
}
并将其添加到 KeyDown 事件中:
input.KeyDown += OnKeyDown;
您可以通过以这种方式添加更多处理程序来链接任意数量的事件处理程序。
这可以在您创建控件后随时完成。要“取消绑定”事件,请从事件中“减去”它:
input.KeyDown -= OnKeyDown;
推荐阅读
- swiftui - 在 SwiftUI 中使用几何阅读器单击卡片时隐藏标签栏
- javascript - 如何与来自消费应用程序的输入共享对象实例?
- java - 在这里如何应用委托?
- python - django模型中与choice和to相关的字段有什么区别?
- linux - ELF 文件中的 build-id 数据偏移量
- python - ImportError:没有名为 sounddevice 的模块
- python - 使用 Python 和 Selenium 抓取难以找到的 Web 表
- python - 在 python 中解码/取消转义 Unicode 实体
- bash - 使用 pm2 延迟启动进程直到 cron 时间
- excel - Excel:将可能不完整的地址组件组合成带有适当分隔符的地址字符串的公式