我想要做的是创建一个包含例如Label和Text框的类 . 它可以有所不同 . 我想动态创建和添加这个obj .
我想将该数据绑定到其属性,并且当然会立即显示更改:
我的步骤是:
-
创建类,例如WpfObject
-
创建新标签
-
创建新的TextBox
-
创建属性
-
包含或不包含参数的构造函数
-
构造函数包含数据绑定设置
我在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(起始位置,左边距,topmargin,root-name,otherparams)它将创建动态提到的这些,我摆脱了每个元素的定位,放入网格 .