【问题标题】:How to change properties of a Control that is in List<UIControl> without using Loop?如何在不使用循环的情况下更改 List<UIControl> 中的控件的属性?
【发布时间】:2011-07-29 02:11:55
【问题描述】:

我有以下代码,其中单击事件会动态地为 WrapPanel 创建额外的 Canvas,并且每个 Canvas 都包含一个 TextBox 和一个 Button。单击一个 Canvas 上的按钮后,TextBox.Text 和 Button.Content 从“Foo”变为“Jesus”。

以下代码有效,但并不理想。因为每个属性都更改(“Foo”为“Jesus”),所以我必须运行一个循环。我必须运行两个循环才能更改 TextBox 和 Button 上的文本。有没有直接的方法来更改属性而不是循环? 我的实际应用程序在 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";
         }
    }
}

【问题讨论】:

    标签: c# wpf list loops


    【解决方案1】:

    只需通过索引访问文本框并直接设置按钮的内容:

    if(bIndex < tbList.Count && bIndex != -1)
        tbList[bIndex].Text = "Jesus";
    if(b != null && bIndex != -1)
        b.Content = "Jesus";
    

    【讨论】:

      【解决方案2】:

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

      tbList[bindex].Text="Jesus";
      

      至于设置按钮内容,您已经拥有来自点击事件的按钮,所以只需使用它:

      b.Content = "Jesus";
      

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

      您可能想要进行一些错误检查,但目前在您现有的代码中也没有这样做。

      Some info on using indexers from MSDN

      【讨论】:

      • 他的代码不需要错误检查!如果 bIndex 为 -1 或 sender 不是按钮,no 将在他的代码中抛出异常...
      • @Daniel,这是正确的,它目前不会设置文本。如果代码不会发生错误情况,则无论如何都可能不需要错误检查。
      猜你喜欢
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多