locked
How to dynamically create and add controls to a page? RRS feed

  • Question

  • Hi,

    I am looking for an example/info on how to dynamically create and load controls into a page.

    My plan is to create a Page in c#. With Blend, to add a ScroolViewer into LayoutRoot of that Page.

    Then, dynamically in the code, to create and add multiple TextBlock/TextBox combinations.

    I would like to use the same page for multiple input scenarios, instead of designing multiple Pages, one for each scenario.

    Thanks,
    EitanB


    • Edited by eitanb Friday, April 12, 2013 5:45 AM
    Friday, April 12, 2013 5:33 AM

Answers

  • Hello,

    You could do something like this:

    XAML:

    <ScrollViewer>    
        <StackPanel x:Name="root" />
    </ScrollViewer>

    Code:

    TextBox myText = new TextBox();
    myText.Text = "Dynamically added control";
    root.Children.Add(myText);


    Kenneth Truyers www.kenneth-truyers.net

    • Proposed as answer by Kenneth Truyers Friday, April 12, 2013 11:48 AM
    • Marked as answer by eitanb Friday, April 12, 2013 4:57 PM
    Friday, April 12, 2013 11:48 AM

All replies

  • Hello,

    You could do something like this:

    XAML:

    <ScrollViewer>    
        <StackPanel x:Name="root" />
    </ScrollViewer>

    Code:

    TextBox myText = new TextBox();
    myText.Text = "Dynamically added control";
    root.Children.Add(myText);


    Kenneth Truyers www.kenneth-truyers.net

    • Proposed as answer by Kenneth Truyers Friday, April 12, 2013 11:48 AM
    • Marked as answer by eitanb Friday, April 12, 2013 4:57 PM
    Friday, April 12, 2013 11:48 AM
  • Hi Kenneth,

    Thanks for you answer.

    One thing I didn't mention in my question but is a must for me, is to bind this control dynamically to data in the page.

    Thanks
    Eitan

    Friday, April 12, 2013 4:04 PM
  • What do you mean by binding dynamically?

    Do you want the list of controls to be a databinding or do you want the data for the controls to be databound?


    Kenneth Truyers www.kenneth-truyers.net

    Friday, April 12, 2013 4:06 PM
  • Hi,

    I would like the data for the controls to be bound TwoWay to string variables in a class.

    I think the code below will do?

    Binding binding = new Binding();
    binding.Mode = BindingMode.TwoWay;
    binding.Source = myClass.myTextSource;
    
    TextBox myText = new TextBox();
    root.Children.Add( myText );
    myText.SetBinding( TextBlock.TextProperty, binding );

    Thanks,
    EitanB


    • Edited by eitanb Friday, April 12, 2013 4:26 PM
    Friday, April 12, 2013 4:18 PM
  • Yeps, 

    exactly. Glad you figured it out!


    Kenneth Truyers www.kenneth-truyers.net

    Friday, April 12, 2013 10:53 PM
  • Thanks,
    EitanB
    Friday, April 12, 2013 10:59 PM