Skip to main content
 首页 » 编程设计

c#之如何在不使用 Loop 的情况下更改 ListUIControl> 中控件的属性

2024年02月23日20qlqwjy

我有以下代码,其中单击事件会动态地为 WrapPanel 创建额外的 Canvas,并且每个 Canvas 都包含一个 TextBox 和一个 Button。单击一个 Canvas 上的 Button 后,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"; 
         } 
    } 
} 

请您参考如下方法:

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

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