开发者

How to change properties of a Control that is in List<UIControl> without using Loop?

I have the following code where a click event will dynamically create additional Canvas to the WrapPanel, and each Canvas contains a TextBox and a Button. Once the Button on one Canvas is click, TextBox.Text and Button.Content change from "Foo" to "Jesus".

The below code works, but it's not ideal. Because each property Change ("Foo" to "Jesus), I have to run a loop. I have to run two loops just to change the text on the TextBox and Button. Is there a direct way to change the Properties other then a Loop? My actually application contains 30+ controls in a Canvas, I don't want to run 30+ loops each time just to change some text.

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 bIn开发者_开发百科dex = 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";
         }
    }
}


Just access the text boxes by index and set the content of the button directly:

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


why can't you just get the item at the index and set that items text:

tbList[bindex].Text="Jesus";

As for setting the buttons content, you already have the button from the click event, so just use that:

b.Content = "Jesus";

You current code just loops through each item in the list and gets the index of the item and sees if it is the index you want. Accessing by the indexer of the list directly will give you what you want.

You will probably want to do some error checking, but that is not currently done in your existing code either.

Some info on using indexers from MSDN

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜