我正在尝试从不同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();
但是window返回null,所以我不能调用方法loadDealProducts。
有没有一种方法可以获得UserControl,而不是使用GetWindow获取窗口?我尝试了Window.GetUserControl和UserControl.GetUserControl,但是没有这样的方法。
sender是来自AddDeal.xaml.cs的DependencyObject,当我单击AddDeal.xaml上的按钮时会得到该from,如下所示:
<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();
}
如您所见,我正在发送button
,它是AddDeal.xaml.cs/xaml上的一个DependencyObject
当它打开一个新的窗口AddDealProduct时,它有AddDealProduct.xaml (UI文件)和它的.xaml.cs代码隐藏文件。在这个文件中,我想从调用UserControl(AddDeal)调用一个函数。
发布于 2019-04-16 05:36:35
好了,我解决了。
我将从源窗口UserControl的Button Click
事件中获得的DependencyObject sender
作为参数发送到另一个UserControl类。
然后,我使用发送器对象解析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);
}
}
希望能有所帮助。
https://stackoverflow.com/questions/55691918
复制相似问题