如何将值从窗口传递到WPF中的UserControl

我想将MainWindow中的值传递给我的UserControl! 我将一个值传递给我的UserControl,UserControl向我展示了MessageBox中的值,但它没有显示TextBox中的值。 这是我的代码:

MainWindow(将值传递给UserControl)

try { GroupsItems abc = null; if (abc == null) { abc = new GroupsItems(); abc.MyParent = this; abc.passedv(e.ToString(), this); } } catch (Exception ee) { MessageBox.Show(ee.Message); } 

用户控件

 public partial class GroupsItems : UserControl { public MainWindow MyParent { get; set; } string idd = ""; public GroupsItems() { InitializeComponent(); data(); } public void passedv(string id, MainWindow mp) { idd = id.ToString(); MessageBox.Show(idd); data(); } public void data() { if (idd!="") { MessageBox.Show(idd); texbox.Text = idd; } } } 

编辑(使用BINDING和INotifyProperty)

…..

  public GroupsItems() { InitializeComponent(); } public void passedv() { textbox1.Text = Text; } } public class Groupitm : INotifyPropertyChanged { private string _text = ""; public string Text { get { return _text; } set { if (value != _text) { _text = value; NotifyPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } 

这里的问题是参考。

在后面的代码中创建新对象时,将创建新对象,这与xaml代码中的对象不同。 所以你应该使用以下代码:

  

在后面的代码中,您不必创建新对象。 您应该使用在XAML中添加的对象:

 ... myGroupsItems.MyParent = this; myGroupsItems.passedv(e.ToString(), this); ... 

这是示例解决方案(sampleproject)。

idd仍为""时,您在构造函数中调用data ,这导致文本框仍为空。 更改MyParent属性不会更改它。 只有passedv 。 但是那时你没有父集。 只需在passedv调用data

试试这个:

 public partial class GroupsItems : UserControl { //properties and methods private string idd=""; public string IDD { get{return idd;} set{ idd=value; textBox1.Text=idd; } } //other properties and methods } 

用法:

在您的主要表格中:

  abc = new GroupsItems(); abc.IDD="sometext"; MainGrid1.Children.Add(abc); //Grid or any other container for your UserControl 

Binding示例中,您的GroupItem类看起来没问题,除了您需要传入已更改属性的名称:

  public string Text { get { return _text; } set { if (value != _text) { _text = value; NotifyPropertyChanged("Text"); } } } 

现在,在GroupsItems ,您不应该访问TextBox 。 在WPF中,我们操纵数据,而不是UI ……但是当我们使用Binding对象将数据绑定到UI控件时,它们会自动更新( 如果我们正确实现了INotifyPropertyChanged接口 )。

首先,让我们在您的代码中添加一个数据属性(它也应该实现INotifyPropertyChanged接口),就像在GroupItem类中一样:

 private GroupItem _item = new GroupItem(); public GroupItem Item { get { return _item; } set { if (value != _item) { _item = value; NotifyPropertyChanged("Item"); } } } 

现在让我们尝试在TextBox.Text属性上使用Binding

  

看看我们如何将GroupItem类的Text属性绑定到TextBox.Text属性…现在我们需要做的就是更改Item.Text属性的值并在UI中观察它的更新:

  ... private void Button_Click(object sender, RoutedEventArgs e) { Item.Text = "Can you see me now?"; } 

或者,如果要在项目的其他位置调用此代码,则可以将此代码放入passedv方法中。 让我知道你是怎么办的。


更新>>>

GroupItem类中,尝试将初始化更改为:

 private string _text = "Any text value"; 

您现在可以在运行应用程序时在UI中看到该文本吗? 如果没有,那么尝试将整个Text属性添加/复制到后面的代码中,并将TextBox声明更改为:

  

如果你现在看不到文本值,你真的遇到了问题……你已经在你的代码中实现了INotifyPropertyChanged接口,不是吗?