如何在WPF中将父usercontrol方法调用到子用户控件中 [英] How to call parent usercontrol method into child user control in WPF

查看:687
本文介绍了如何在WPF中将父usercontrol方法调用到子用户控件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有另一个UserControl内的UserControl。让我们称他们为ParentUC和ChildUC。我需要从ChildUC获得ParentUC。可以任何人帮助我,如何实现这个目标?



我尝试过:



任何人都可以给我发送一些这个任务的链接。

I have a UserControl that inside of another UserControl. Lets call them ParentUC and ChildUC. I need to get ParentUC from ChildUC.Can Anyone help me ,how to achieve this?

What I have tried:

Can anyone send me some links for this task.

推荐答案

这里有一个想法/方式如何解决你的请求找到父控件。



中捕获父控件OnVisualParentChanged

Here an idea/way how you can solve your request to find the parent control.

Capture the parent control in OnVisualParentChanged:
public partial class ChildUserControl : UserControl
{
    private ParentUserControl parentUserControl = null;

    protected override void OnVisualParentChanged(DependencyObject oldParent)
    {
        // Base Class
        base.OnVisualParentChanged(oldParent);

        // Parent Control
        parentUserControl = this.Parent as ParentUserControl;
    }

    // ....
    void DoSomethingWithParent()
    {
        // >>>Don't forget to check whether parent capturing was successful<<< 
        if (parentUserControl != null)
        {
           parentUserControl.ParentMethod();   
        }
    }
}





家长控制XAML,注意:孩子不应该在例如上面代码的网格。



Parent Control XAML, note: child should not be in e.g. a grid for the code above.

<usercontrol>
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication4" x:Class="MyWPFControls.ParentUserControl" 
             mc:Ignorable="d" Height="159.2" Width="209.6" Background="#FFD8BBBB">
    <local:childusercontrol horizontalalignment="Left" height="32" margin="147,117,0,0" verticalalignment="Top" width="53" xmlns:local="#unknown">

Background="#FFB28484"/>
</local:childusercontrol></usercontrol>



我希望它有所帮助。


I hope it helps.


这篇关于如何在WPF中将父usercontrol方法调用到子用户控件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆