首页 > 解决方案 > 用于输入的 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通过检查输入按钮按下动态名称来“绑定”触发事件()。有人可以帮我吗?

标签: c#wpfdynamic

解决方案


您通过添加到控件的适当事件来“绑定”触发事件 - 在这种情况下,您需要创建一个方法,例如:

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;

推荐阅读