WPF将数据从Window传递到正在运行的用户控件

时间:2018-05-27 05:39:20

标签: c# wpf

我是WPF世界的新手。我的内部有UserControlButton。单击按钮后,选择器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; } } } 来创建新窗口。

1 个答案:

答案 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);
}

希望它有效!