用于输入的C#WPF动态名称



因此,我尝试动态添加输入并从中检索日期,并且只有当用户在输入中按下回车键时才执行操作。所以,我目前正在做的是将输入附加到堆栈中。这很好用。命名也是有效的。我使用以下功能;

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;

最新更新