我是WPF世界的新手。我的内部有UserControl
和Button
。单击按钮后,选择器Window
将在新窗口中打开并同时与UserControl
一起运行
当用户选择一个值时,我希望在第二个window
中,将此值传递回UserControl
,然后关闭窗口。我怎样才能做到这一点? DataBinding是INotifyPropertyChanged
类的最佳方式吗?我该如何实现呢?
溶液
从Microsoft文档和delegate
以及EventHandler
含义,我执行以下操作。我有一个名为UserControl
的{{1}}。当用户点击BuyFactor
名为Add Item
的{{1}}新Window
时。选择新项目并点击AddItem
后,我想通过Add This
将项目ID发回BuyFactor
:
EventHandler
UserControl:
BuyFactor
AddItem窗口:
public partial class BuyFactor: UserControl
{
Dialogs.AddItem publisher;
public TaqehBuyFactor()
{
InitializeComponent();
publisher = new Dialogs.AddItem();
publisher.RaiseCustomEvent += HandleCustomEvent;
}
void HandleCustomEvent(object sender, Dialogs.CustomEventArgs e)
{
//Should change text when button clicked on Window (publisher)
ProductName.Text = e.Message;
}...}
和我的 public partial class SelectTaqehDialog : Window
{
public event EventHandler<CustomEventArgs> RaiseCustomEvent;
public void DoSomething()
{
// Write some code that does something useful here
// then raise the event. You can also raise an event
// before you execute a block of code.
OnRaiseCustomEvent(new CustomEventArgs("Did something"));
}
protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
// Event will be null if there are no subscribers
if (handler != null)
{
// Format the string to send inside the CustomEventArgs parameter
e.Message += String.Format(" at {0}", DateTime.Now.ToString());
// Use the () operator to raise the event.
handler(this, e);
}
}
private void addToFactor_Click(object sender, RoutedEventArgs e)
{
// Fire when Add This button clicked
DoSomething();
}
:
CustomEventArgs
请注意调用public class CustomEventArgs : EventArgs
{
public CustomEventArgs(string s)
{
message = s;
}
private string message;
public string Message
{
get { return message; }
set { message = value; }
}
}
来创建新窗口。
答案 0 :(得分:1)
// in MainWindow or somewhere
myUserControl.someBtn.Click += (se, a) => {
var mw = new MyWindow();
mw.Show();
mw.myEvent += (myEventSender, myComboBoxFomMyWindow) => MessageBox.Show(myComboBoxFromMyWindow.SelectedItem as string);
};
// MyWindow
public event EventHandler<ComboBox> MyEvent;
public MyWindow() {
myComboBox.SelectionChanged += (se, a) => MyEvent?.Invoke(this, myComboBox);
}
希望它有效!