wpf - 从另一个 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();
}
如您所见,我正在发送button
AddDeal.xaml.cs/xaml 上的 DependencyObject
当它打开一个新窗口 AddDealProduct 时,它具有 AddDealProduct.xaml(UI 文件)及其 .xaml.cs 代码隐藏文件。在这个文件中,我想从调用 UserControl(AddDeal) 中调用一个函数。
解决方案
好的,我解决了。
我将从源窗口 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);
}
}
希望能帮助到你。
推荐阅读
- django - 如何为 Vue 和 Django 配置 NGINX?
- django - 哪个模板标签包含使用 django-storage[dropbox] 存储的图像
- javascript - 向下滚动 5 div 主页时有轻微的抖动
- sql - 使用 group by 从表中选择字段名称的结果
- mysql - 如何在 phpmyadmin 中设置没有错误的表?
- javascript - 如何制作带有滚动条的引导媒体列表?
- jupyter-notebook - 从外部访问 Jupyter 笔记本 - 如何允许 google colab 访问本地主机 Jupyter 笔记本?
- python - 如何将 timedelta 转换为小时
- c# - SQL Server 数据库连接字符串问题在不同机器上运行应用程序
- react-native - React Native:模态屏幕的暗背景