我的用户控件由于空字段而无法启动,我真的很生气,我的代码位于:
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
时?
答案 0 :(得分:1)
在WPF中,这类事情通常是通过数据绑定完成的,但是只需在用户控件上设置属性,然后再将其添加到面板中,即可快速完成此工作。
向用户控件添加属性:
public string TextBlockString
{
get
{
return this.textBlock2.Text;
}
set
{
this.textBlock2.Text = value;
}
}
然后在btnGeneral_Click
:
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;
MyControl myControl = _userControls[button.Tag.ToString()];
myControl.TextBlockString = textBox1.Text;
PanelMainContent.Children.Add(myControl);
}