我有以下代码,其中click事件将为WrapPanel动态创建其他Canvas,并且每个Canvas都包含一个TextBox和一个Button。单击一个画布上的Button后,TextBox.Text和Button.Content从“ Foo”更改为“ Jesus”。

下面的代码有效,但是并不理想。因为每个属性都会更改(从“ Foo”更改为“ Jesus”),所以我必须运行一个循环。我必须运行两个循环才能更改“文本框”和“按钮”上的文本。 ?我的实际应用程序在Canvas中包含30多个控件,我不想每次只更改一些文本就运行30多个循环。

List<Canvas> cvList = new List<Canvas>();
List<TextBox> tbList = new List<TextBox>();
List<Button> FooList = new List<Button>();
WrapPanel wp = new WrapPanel();

private void createbtn1_Click(object sender, RoutedEventArgs e)
{
    Canvas cv = new Canvas();
    StackPanel sp = new StackPanel();
    TextBox tb = new TextBox();
    Button Foo = new Button();

    sp.Orientation = Orientation.Vertical;
    sp.Children.Add(tb);
    sp.Children.Add(Foo);
    cv.Children.Add(sp);
    wp.Children.Add(cv);
    cvList.Add(cv);
    tbList.Add(tb);
    FooList.Add(Foo);

    cv.Width = 100;
    cv.Height = 100;

    tb.Text = "#" + (cvList.IndexOf(cv)+1);
    tb.Width = 50;
    tb.Height = 30;

    Foo.Content = "Foo";
    Foo.Click += destroy_Click;
}

private void Foo_Click(object sender, RoutedEventArgs e)
{
    Button b = sender as Button;
    var bIndex = FooList.IndexOf(b);


    foreach (TextBox t in tbList)
    {
        if (tbList.IndexOf(t) == bIndex)
        {
            t.Text = "Jesus";


           }
        }
    foreach (Button f in FooList)
    {
        if (FooList.IndexOf(t) == bIndex)
        {
            t.Content = "Jesus";
         }
    }
}

最佳答案

为什么不能只在索引处获取项目并设置该项目的文本:

tbList[bindex].Text="Jesus";


至于设置按钮的内容,您已经拥有click事件中的按钮,因此只需使用它即可:

b.Content = "Jesus";


您当前的代码只是循环遍历列表中的每个项目,并获取该项目的索引,然后查看它是否为您想要的索引。由列表的索引器直接访问将为您提供所需的内容。

您可能需要进行一些错误检查,但是当前在现有代码中也未执行。

Some info on using indexers from MSDN

关于c# - 如何在不使用循环的情况下更改List <UIControl>中的控件的属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5537472/

10-11 22:31
查看更多