由于空字段,我的用户控件无法启动,我真的很生气,我的代码如下:
public MyControl()
{
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
string userinputMainWindow = (string)App.Current.Properties["TextBoxString"];
Foreach
{
TextBlock textBlock2 = new TextBlock();
textBlock2.Text = String.Format(userinputMainWindow); // null
textBlock2.TextAlignment = TextAlignment.Left;
但我不认为这是我需要的,我怎样才能阻止代码在启动时初始化并且只在我调用代码时进行初始化?
例如,在我的主窗口上,我这样调用用户控件:
private Dictionary<string, UserControl> _userControls = new Dictionary<string, UserControl>();
public Dictionary<string, UserControl> GetUserControls()
{
return _userControls;
}
public MainWindow()
{
InitializeComponent();
List<string> userControlKeys = new List<string>();
userControlKeys.Add("MyControl");
Type type = this.GetType();
Assembly assembly = type.Assembly;
foreach (string userControlKey in userControlKeys)
{
string userControlFullName = String.Format("{0}.UserControls.{1}", type.Namespace, userControlKey);
UserControl userControl = (UserControl)assembly.CreateInstance(userControlFullName);
_userControls.Add(userControlKey, userControl);
}
}
private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
App.Current.Properties["TextBoxString"] = textBox1.Text;
PanelMainContent.Children.Clear();
Button button = (Button)e.OriginalSource;
Type type = this.GetType();
Assembly assembly = type.Assembly;
PanelMainContent.Children.Add(_userControls[button.Tag.ToString()]);
}
有没有办法停止用户控件初始化,只有当我点击btnGeneral_Click
?