动态添加WPF内容

时间:2018-10-28 11:22:15

标签: c# wpf data-binding dynamically-generated

我想做的是创建一个包含例如Label and Text框的类。可能会有所不同。我想动态创建并添加此obj。

我想将该数据绑定到其属性,并且当然可以立即显示更改:

我的步骤是:

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

我按照wpf-tutorial页面上的WPF教程进行了检查,还检查了msdn的提示,并尝试做类比而不忘记任何步骤。当然,我尝试用Google搜索问题所在。

通过调试,我发现onPropertyChanged分别对应。 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(起始位置,左边距,topmargin,根名,otherparams),它将动态创建提及的内容,并且我摆脱了将每个元素放到网格中的位置。

0 个答案:

没有答案
相关问题