首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从另一个UserControl调用UserControl方法

从另一个UserControl调用UserControl方法
EN

Stack Overflow用户
提问于 2019-04-15 22:56:03
回答 1查看 403关注 0票数 0

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

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

代码语言:javascript
复制
        public void loadDealProducts()
        {
            InfoBox.Information("loadDealProducts called.", "testing");
        }

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

代码语言:javascript
复制
            Window window = null;
            if (sender is Window)
                window = (Window)sender;
            if (window == null)
                window = Window.GetWindow(sender);
            return window;

          (window as AddDeal).loadDealProducts();

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

有没有一种方法可以获得UserControl,而不是使用GetWindow获取窗口?我尝试了Window.GetUserControl和UserControl.GetUserControl,但是没有这样的方法。

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

代码语言:javascript
复制
<Button Click="BtnAddProducts" CommandParameter="{Binding Path=ProductID}">Add Product</Button>

它调用以下代码:

代码语言:javascript
复制
        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();
        }

如您所见,我正在发送button,它是AddDeal.xaml.cs/xaml上的一个DependencyObject

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

EN

回答 1

Stack Overflow用户

发布于 2019-04-16 05:36:35

好了,我解决了。

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

然后,我使用发送器对象解析UserControl,并从不同的UserControl类调用其类中的函数。

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

代码语言:javascript
复制
AddDealUserControl ownerx2 = FindVisualParent<AddDealUserControl>(sender);
ownerx2.loadDealProducts();

FindVisualParent帮助器类:

代码语言:javascript
复制
        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);
            }
        }

希望能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55691918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档