【WPF】WPF中UserControl如何访问它所属的Window的控件或事件

问题提出:
现在做了个UserControl,能实现保存数据的功能,但是保存完了,需要更新MainWindow的数列表数据

问题解决:
经过我的研究,发下用WPF的事件能够很好的解决这个问题。原理是让Window主窗口监听所有的Button事件(包括它所有的UserControl),根据需要来执行相应的操作。

1、在Window的构造函数中添加按钮监听事件

public static string comType;

public MainWindow()
    {
     
        InitializeComponent();
        this.AddHandler(Button.ClickEvent, new RoutedEventHandler(ButtonClicked));
    }

2、在Window中实现这个事件

#region 其他组件事件监听
/// 
/// 其他组件事件监听
/// 
/// 
/// 
private void ButtonClicked(object sender, RoutedEventArgs e)
{
     
    switch (comType)
    {
     
        case "Save":
            // 处理自己的逻辑
            break;
        default:
            break;
    }
    comType = string.Empty; // 处理完了置空这个
}
#endregion

这里我定义了一个字符串类型comType来设置需要监听的事件类型,如果不需要监听,则可以在按钮事件里,将事件类型设置为""。这样当MainWindow监听到事件后,也会忽略掉。在Window执行完操作后,也会将事件类型设置为"",否则只要有按钮事件就会继续执行。

3、在UserControl中需要被传递的事件中里设置事件类型和相关的参数

private void Save_Click(object sender, RoutedEventArgs e)
{
     
     WindowSave windowSave = new WindowSave();
     if (windowSave.ShowDialog() == true)
     {
     
         string pid = windowSave.txt_ParentId.Text;
         string proId = StringUtils.obj2Str(projId);
         string url = textBoxUrl.Text;
         string name = windowSave.txt_ModuleName.Text;
         string method = StringUtils.obj2Str(this.comboBoxMethod.SelectedValue);
         TextRange textRange = new TextRange(richTextParam.Document.ContentStart, richTextParam.Document.ContentEnd);
         string body = textRange.Text;
         Functions.createModule(pid, proId, url, name, body, method);
         MainWindow.comType = "Save";
     }
 }

OK,成功了,当在UserControl里点击了Save_Click按钮时候,首先将参数传递给MainWindow,然后设置类型。MainWindow在监听到事件后通过switch来执行响应的操作,然后在将类型设置为""。

你可能感兴趣的:(NetCore)