I am guessing you want to add controls to the UI dynamically.
Since you have to set a property in the Control
i.e. for TextBox
you have to set the Text
property, for Label
you have you set the Content
property. I suggest the following approach.
In the below sample I add a textbox and label to the UI dynamically.
The important piece in the below code is the Dictionary<Type, Action<Control, String>>
property. In this Dictionary
I define how to set the content for each Control
depending on its Type
.
Note:
I would suggest you to design in such a way that you don't separate the instance creation and property assignment into two different method. Do it in one single go. Check the new method with signature getObjectClass(string type, String content, Thickness margin).
XAML:
<Window x:Class="SplashScreenDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="800">
<StackPanel Name="StackPanelObj">
</StackPanel>
</Window>
Codebehind:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace SplashScreenDemo
{
public partial class MainWindow : Window
{
Dictionary<Type, Action<Control, String>> SetContent = new Dictionary<Type, Action<Control, String>>
{
{ typeof(TextBox), (control, content) => (control as TextBox).Text = content},
{ typeof(Label), (control, content) => (control as Label).Content = content}
};
public MainWindow()
{
InitializeComponent();
Control control = getObjectClass("textbox");
SetContent[control.GetType()](control, "This is a textbox");
Control control2 = getObjectClass("label");
SetContent[control2.GetType()](control2, "This is a label");
StackPanelObj.Children.Add(control);
StackPanelObj.Children.Add(control2);
}
public Control getObjectClass(string type)
{
switch (type)
{
case "textbox":
return new TextBox();
case "label":
return new Label();
default:
return null;
}
}
public Control getObjectClass(string type, String content, Thickness margin)
{
switch (type)
{
case "textbox":
var textBox = new TextBox();
textBox.Text = content;
textBox.Margin = margin;
return textBox;
case "label":
return new Label();
default:
return null;
}
}
}
}