【发布时间】:2016-07-01 23:35:40
【问题描述】:
我想将一个值从 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));
}
}
【问题讨论】:
-
老兄...您正在尝试像使用 WinForms 一样使用 WPF。它只是不能那样工作。在编写更多 WPF 之前,请先了解如何使用数据
Binding和INotifyPropertyChangedinterface。 -
@Sheridan 如果他不想,我认为他不必使用
Binding、MVVM 等。我同意你的观点,这是终极体验,但仍然可以使用旧模式。 -
@Sheridan 我使用绑定的代码也不起作用:(
-
@meilke,我完全接受一切皆有可能。请注意,我没有提到 MVVM 或终极体验。只是问题作者如果用 WPF 方式而不是他当前使用的 WinForms 方式编写 WPF,会发现 WPF 更容易编写。
-
@Sheridan 请花点时间查看我更新的代码
标签: c# wpf user-controls