How can I load a user control[s] in a window dynamically (using code at runtime)?
Retaining the dynamic controls on PostBack In order to retain the dynamic TextBoxes across PostBacks, we need to make use of Page's PreInit event to recreate the dynamic TextBoxes using the Request.
After adding control in tool box you can drag and drop control in your form where you want to use this control. Its my user control you can make own user control according to own requirement. If you want to get the custom control selected value and selected text write this code.
The DynamicControl control is used by templated data-bound controls, such as FormView or ListView, to display a data field that uses ASP.NET Dynamic Data features in a custom page. You can also use a DynamicControl control in a TemplateField field of a GridView or a DetailsView control.
User controls. User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. Custom controls. A custom control is a class that you write that derives from Control or WebControl.
I'd highly recommend having a look at Prism, since composite user interfaces is what it's for. However, since this would require you refactoring your entire application, I'll also answer your question directly.
If you want a single user control in a container, put a ContentControl in your XAML and then set the Content property. If you are using a view model, you could bind Content to a FrameworkElement property on the view model:
contentControlInstance.Content = new CustomUserControl();
If you want multiple controls in a list, use an ItemsControl and assign an ObservableCollection<> to the ItemsSource property. If you are using a view model, you could bind ItemsSource to an ObservableCollection property on the View Model.
Then you can just add/remove views from that ObservableCollection:
private ObservableCollection<FrameworkElement> views =
new ObservableCollection<FrameworkElement>();
private void Initialize()
{
itemsControl.ItemsSource = views;
}
private void AddView(FrameworkElement frameworkElement)
{
views.Add(frameworkElement);
}
For adding multiple controls you need container.
Suppose you have a StackPanel container "myStack"
<Window ..>
<StackPanel Name="MyStack" />
</Window>
You can create control dynamically and add it to container. See code below
void AddButtons()
{
Button B1=new Button(),B2=new Button(), B3=new Button();
B1.Content="Hello";
B2.Content="First";
B3.content="Application";
// Now you can set more properties like height, width, margin etc...
MyStack.Children.Add(B1);
MyStack.Children.Add(B2);
MyStack.Children.Add(B2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With