6

我有多个 XAML TextBoxes,每个 XAML es 操作数组中的相应值,当TextBox更改中的值时,使用C#动态检查TextBox调用该方法的方法。

    <TextBox x:Name="_0_0" TextChanged="_x_y_TextChanged"/>
    <TextBox x:Name="_0_1" TextChanged="_x_y_TextChanged"/>
    <TextBox x:Name="_0_2" TextChanged="_x_y_TextChanged"/>
    // And so on.....

每个都在数组中操作一个对应的值,当值TextBox改变时,使用 C# 方法动态检查哪个TextBox调用了该方法。

    private void _x_y_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox current = (TextBox)sender;
        string currentname = current.Name;
        string rowstring = currentname.Substring(1, 1);

        string columnstring = currentname.Substring(3, 1);

        int row = Convert.ToInt32(rowstring);
        int column = Convert.ToInt32(columnstring);

        // I've then detected the name of the textbox which has called it...

因此,此信息可用于将来自 a 的信息动态存储TextBox在相应的数组索引中 - 或者您想要使用它做的任何事情......

然而,我的问题是:

如何创建一个使用数组中的索引位置的方法来调用相关TextBox并更新其文本?

4

4 回答 4

8

用于FindName(string)按名称查找文本框,如下所示(其中container是包含所有文本框的控件):

private void UpdateTextBox(int row, int column, string text)
{
    TextBox textBox = container.FindName("_" + row + "_" + column) as TextBox;
    if(textbox != null)
    {
        textbox.Text = text;
    }
}
于 2012-12-29T03:52:58.547 回答
3

你可能有两种方法:

如果你有很多数据要管理,或者如果你无法预测数组的长度,最好绑定到一个集合而不是手动将数据插入和取出数组。如果您创建从 ObservableCollection 派生的类而不是使用数组,则数据 <> ui 关系非常简单。

如果您真的需要手动执行此操作,也许最好将索引粘贴到文本框的“标签”字段中。您可以 (a) 在您的 xaml 中清楚地看到它,(b) 轻松解析它并且 (c) 如果您在此处使用公式的变体:

按类型查找 WPF 窗口中的所有控件

您可以遍历窗口中的文本框并通过查看其标签索引找到正确的文本框:

    foreach (TextBox t in FindVisualChildren<TextBox>(this))
    {
        if ((int) t.Tag)  == my_index )
        {
            t.Text = "my_text_goes_here";
         }
    }
于 2012-12-29T09:18:51.510 回答
1

我会朝着我在这个问题上给出的答案的方向前进: form anchor/dock 简而言之,我将创建一个包含实际值的类,然后创建一个包含信息类的集合。

然后我不会在 TextBoxes 上使用事件“TextChanged”,而是“嗅探”用于保存文本的依赖属性的更改。这可以在依赖属性中轻松完成。

最后,我会使用 ItemsControl 或 ItemsPresenter 来显示控件。控件的数量将跟随集合中的项目数量。

于 2012-12-29T10:34:42.277 回答
0

我建议使用 MVVM 模式、数据模板和 ItemsControl 来有效地处理这个问题。

于 2012-12-29T05:35:28.423 回答