调用注入接口方法

时间:2015-12-04 20:30:55

标签: c# mvvm unity-container

我有一个名为'CloseTabAction'的类,它允许我使用'Yes,No和Cancel'按钮来提出一个对话框。我能够提出这个对话框是因为我使用了'Implementor'方法,它允许我从IRequestTabItemClose接口引发对话,因为它是由我的ViewModel实现的。

请参阅下面的课程以便更好地理解:

internal class CloseTabAction : TriggerAction<Button>
{
    protected override void Invoke(object parameter)
    {
        var args = parameter as RoutedEventArgs;
        if (args == null) return;

        var tabItem = FindParent<TabItem>(args.OriginalSource as DependencyObject);
        if (tabItem == null) return;

        tabItem.IsSelected = true;

        var tabControl = FindParent<TabControl>(tabItem);
        if (tabControl == null) return;

        var region = RegionManager.GetObservableRegion(tabControl).Value;
        if (region == null) return;

        var content = Implementor<IRequestTabItemClose>(tabItem.Content);
        if (content == null) return;

        if (IsDirty(content))
        {
            RaiseConfirmDialog(content, region, tabItem);
        }
        else
        {
            region.Remove(tabItem.Content);
        }
    }

    private static void RaiseConfirmDialog(IRequestTabItemClose content, IRegion region, TabItem tabItem)
    {
        content.ConfirmCloseRequest((canSave, cancel) =>
        {
            if (cancel) return;
            if (canSave)
            {
                // repo.Save();
                region.Remove(tabItem.Content);
                return;
            }
            region.Remove(tabItem.Content);
        });
    }

    private static bool IsDirty(IRequestTabItemClose content)
    {
        var isContentDirty = false;

        content?.IsContentDirty(isDirty =>
        {
            if (isDirty)
                isContentDirty = true;
        });
        return isContentDirty;
    }

    private static T FindParent<T>(DependencyObject child) where T : DependencyObject
    {
        while (true)
        {
            var parentObject = VisualTreeHelper.GetParent(child);

            if (parentObject == null) return null;

            var parent = parentObject as T;
            if (parent != null) return parent;

            child = parentObject;
        }
    }

    private static T Implementor<T>(object content) where T : class
    {
        T implementor = content as T;
        if (implementor != null) return implementor;

        var element = content as FrameworkElement;
        if (element != null) implementor = element.DataContext as T;
        return implementor;
    }
}

现在我想在我的IRepositry界面中调用save方法,但是我正在使用Unity的依赖注入。

    public MyViewViewModel(IRepository iRepository)
    {
        _iRepository = iRepository;
    }

这意味着我无法使用'Implemetor'方法。然后,如何在'CloseTabAction'中为我当前的ViewModel从IRepository调用save方法?

0 个答案:

没有答案