0

由于空字段,我的用户控件无法启动,我真的很生气,我的代码如下:

       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

4

1 回答 1

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);
}
于 2012-04-18T14:56:15.283 回答