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

罗宾

因此,我试图动态添加输入内容并从中获取日期,并且仅当用户在输入中按Enter时才执行操作。所以,我目前正在做的就是将输入追加到stacklayout上。效果很好。命名也可以。我使用以下功能;

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通过动态名称来按Enter按钮来“绑定”触发事件()。有人可以帮我吗?

保罗

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

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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章