从同一用户控件处置用户控件

时间:2014-08-26 06:31:33

标签: c# wpf

我有wpf应用程序有Mainform,我正在动态添加自定义用户控件;自定义用户控件hase关闭按钮应该处理usercontrol.I我无法从自己处理相同的usercontrol(我怎么能在winform中这样做应用)。现在我正在使用自定义事件委托来实现这个功能(从主窗口,通过从网格中删除控件)。

任何人都可以提出更好的方法吗?

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for ChildControl.xaml
/// </summary>
public partial class ChildControl : UserControl
{
    public delegate void onCloseOfControl();
    public event onCloseOfControl CloseBtnEvent;

    //This control will be added into
    // grid of Mainwindow.
    public ChildControl()
    {
        InitializeComponent();
    }

    //I want to remove this whole control
    private void btnCloseOnChild_Click(object sender, RoutedEventArgs e)
    {
        //this.Dispose();
        //Not Possible In wpf,I could do this in Winforms.

        //Now I am wrting this logic

        if (CloseBtnEvent != null)
            CloseBtnEvent();
        //Now main window will get this event,and I will
        //remove this control from grid.
    }

 }
}

2 个答案:

答案 0 :(得分:2)

一般情况下,在WPF中,UserControl需要被处理......他们实施{ {3}}。他们包含任何需要处置的服务或其他成员。 WPF UserControl与WinForms UserControl几乎没有相似之处,越早停止将WPF与WinForms进行比较,就越能学会WPF。

删除或替换UserControl的简单行为足以释放它可能占用的任何资源。我们经常在WPF中使用DataTemplate来让框架为我们显示UserControl

<DataTemplate DataType="{x:Type ViewModels:UsersViewModel}">
    <Views:UsersView />
</DataTemplate>

...

<ContentControl Content="{Binding ViewModel}" />

执行此操作时,您需要做的就是更换UserControl

ViewModel = new UsersViewModel();

答案 1 :(得分:0)

当你点击关闭按钮时,你的UserControl应该实现一个触发事件。然后,您的表格应通过处置控件对此事件作出反应。您无法从内部处置控件。

相关问题