首页 > 解决方案 > 动态添加 WPF 内容

问题描述

我想做的是创建一个包含例如标签和文本框的类。它可以不同。我想动态创建和添加这个 obj。

我想将该数据绑定到它的属性,当然会立即显示更改:

我的步骤是:

  1. 创建类,例如 WpfObject
  2. 创建新标签
  3. 创建新的文本框
  4. 创建属性
  5. 带或不带参数的构造函数
  6. 构造函数包含数据绑定设置

我在 wpf-tutorial 页面上关注了 WPF 教程,还检查了 msdn 的提示,并尝试类推,不要忘记任何步骤。当然,我试图用谷歌搜索问题所在。

通过调试,我刚刚发现 onPropertyChanged resp。PropertyChanged 仍然返回 null。

好吧,我不知道我要看什么。我试图从此处或网络上陈述的其他问题中学习一些东西,但可能我理解错误或忘记了一些东西。

所以想请教一些提示,或者帮助。

在这里我添加我的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    List<infoObject> LinfoObjectList = new List<infoObject>();

    private void btnAddBox_Click(object sender, RoutedEventArgs e)
    {
        infoObject theObject = new infoObject("theinfo");
        LinfoObjectList.Add(theObject);
        mainGrid.Children.Add(theObject.AddLabel());
        mainGrid.Children.Add(theObject.AddTextbox());
    }

    private void btnCustomBox_Click(object sender, RoutedEventArgs e)
    {
        foreach(var item in LinfoObjectList)
        {
            item.ChangeInfoObject();
        }
    }
}

public class infoObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    string _sTheText;

    string STheText
    {
        set { _sTheText = value;
            OnPropertyChanged("sTheText");
        }

        get { return _sTheText; }
    }

    Label theLabel = new Label();
    TextBox theTextBox = new TextBox();

    int i;

    public infoObject(string _objectName){
        STheText = " ";
        i = 0;
        theLabel.Width = 100;
        theLabel.Height = 25;
        theLabel.Content = _objectName;

        theTextBox.Width = 100;
        theTextBox.Height = 30;
        theTextBox.Text = STheText.ToString();


        Binding binding = new Binding();
        binding.Path = new PropertyPath("sTheText");
        theTextBox.SetBinding(TextBox.TextProperty, binding);
    }

    public void ChangeInfoObject()
    {
        STheText = "textWasChanged"+i.ToString();
        i = +1;
    }

    public Label AddLabel()
    {
        return this.theLabel;
    }

    public TextBox AddTextbox()
    {
        return this.theTextBox;
    }

    public void OnPropertyChanged(string propName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

编辑:澄清我想做什么:

我想做一些图书馆或某事。就像那样,将来我将能够创建文本框、标签、按钮,例如我存储在列表或其他地方的每个元素。

因此,我将添加例如 Element.add(starting position , left margin ,topmargin, root-name , otherparams) ,它将动态创建提到的这些,并且我摆脱了每个元素的定位,放入网格中。

标签: c#wpfdata-bindingdynamically-generated

解决方案


推荐阅读