首页 > 解决方案 > 从另一个 UserControl 调用 UserControl 方法

问题描述

我正在尝试从不同的 UserControl 调用来自 UserControl 的方法。我无法跟踪我试图从中调用该方法的 UserControl 来调用该方法。

我正在尝试调用 AddDeal.xaml.cs 中的以下方法

        public void loadDealProducts()
        {
            InfoBox.Information("loadDealProducts called.", "testing");
        }

我正在跟踪 AddDeal UserControl 并尝试使用以下方法在文件 AddDealProducts.xaml.cs 中调用方法 loadDealProducts()

            Window window = null;
            if (sender is Window)
                window = (Window)sender;
            if (window == null)
                window = Window.GetWindow(sender);
            return window;

          (window as AddDeal).loadDealProducts();

但是窗口返回 null 所以我不能调用方法 loadDealProducts。

除了使用 GetWindow 获取 Window 之外,有没有获取 UserControl 的方法?我尝试了 Window.GetUserControl 和 UserControl.GetUserControl 但没有这样的方法。

sender 是来自 AddDeal.xaml.cs 的 DependencyObject,当我单击 AddDeal.xaml 上的按钮时,我得到如下:

<Button Click="BtnAddProducts" CommandParameter="{Binding Path=ProductID}">Add Product</Button>

它调用以下内容:


        private void BtnAddProducts(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender as DependencyObject;
            Window AddProductsDialog = new Window {
                Title = "Add Products to Deal",
                Content = new AddDealProduct(button, productID, false, 0)
            };
            AddProductsDialog.ShowDialog();
        }


如您所见,我正在发送buttonAddDeal.xaml.cs/xaml 上的 DependencyObject

当它打开一个新窗口 AddDealProduct 时,它具有 AddDealProduct.xaml(UI 文件)及其 .xaml.cs 代码隐藏文件。在这个文件中,我想从调用 UserControl(AddDeal) 中调用一个函数。

标签: wpfmethodscall

解决方案


好的,我解决了。

我将从源窗口 UserControl 的事件DependencyObject sender中获得的Button Click 一个作为参数发送到另一个 UserControl 类。

然后我使用 sender 对象来解析 UserControl 并从不同的 UserControl 类调用其类中的函数。

要调用该函数,我执行以下操作:

AddDealUserControl ownerx2 = FindVisualParent<AddDealUserControl>(sender);
ownerx2.loadDealProducts();

FindVisualParent 助手类:

        public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
        {
            // get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);

            // we’ve reached the end of the tree
            if (parentObject == null) return null;

            // check if the parent matches the type we’re looking for
            T parent = parentObject as T;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                // use recursion to proceed with next level
                return FindVisualParent<T>(parentObject);
            }
        }

希望能帮助到你。


推荐阅读