Master/Detail 工具栏命令绑定

Master/Detail Toolbar Command binding

我有以下带有工具栏、大师列表和详细视图的应用程序:

详情 "injected" 通过 ContentControl。 detail包含一个UserControl,里面包含一个ScrollViewer等等。在某些时候,有一个 "ZoomPanControl" (不是我的)提供了一个命令 "FitView".

我想从我的工具栏为当前活动的详细视图执行命令 "FitView"。

我的工具栏按钮如下所示:

<fluent:Button x:Name="FitButton" Command="{Binding ?WhatGoesHere?}" Header="Fit View"/>

我不知道如何将工具栏按钮的命令 属性 绑定到当前活动的 ZoomPanControl。在执行命令绑定时,我什至"see"都没有这个控件。

非常感谢任何提示如何解决这个问题。

public static class WpfHelper
{        
    public static IEnumerable<DependencyObject> GetVisualChildsRecursive(this DependencyObject parent)
    {
        if (parent == null)
            throw new ArgumentNullException("parent");

        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            var v = VisualTreeHelper.GetChild(parent, i);

            yield return v;

            foreach (var c in GetVisualChildsRecursive(v))
                yield return c;
        }
    }
}

//命令执行

    this.DetailView.GetVisualChildsRecursive().OfType<ZoomPanControl>().First().FitView();

//命令可以执行

    this.DetailView.GetVisualChildsRecursive().OfType<ZoomPanControl>().Any();

这是我解决问题的方法。幸运的是我可以访问 ZoomPanControl 的源代码。

首先,我在 ZoomPanControl 中为 "FitView" 命令实现了一个 DependencyProperty,如下所示:

public static readonly DependencyProperty FitCommandDepPropProperty =   DependencyProperty.Register(
        "FitCommandDepProp", typeof (ICommand), typeof (ZoomAndPanControl),   new PropertyMetadata(default(ICommand)));

    public ICommand FitCommandDepProp
    {
        get { return (ICommand) GetValue(FitCommandDepPropProperty); }
        set { SetValue(FitCommandDepPropProperty, value); }
    }

在控件的"OnApplyTemplate()"方法中我设置了依赖属性:

FitCommandDepProp = FitCommand;

在我的应用程序的详细视图中,我将命令依赖项-属性 绑定到我的 ViewModel,如下所示:

<zoomAndPan:ZoomAndPanControl x:Name="zoomAndPanControl" 
                                      FitCommandDepProp="{Binding FitCommand, Mode=OneWayToSource}"

重要的部分是Mode=OneWayToSource。这 "forwards" 从 ZoomPanControl 到我的细节视图模型的命令。

Detail-viewmodel 有 属性 个要绑定的 ICommand。从这一点开始,我的视图模型逻辑中就有了命令。我已经实现了一种将 FitCommand 传递给绑定到工具栏的视图模型的机制。您可以使用事件或任何您喜欢的方式来传递命令。

工具栏的视图模型再次为 FitCommand 提供了一个 ICommand 属性。

public ICommand FitCommand
    {
        get { return _fitCommand; }
        set
        {
            if (Equals(value, _fitCommand)) return;
            _fitCommand = value;
            NotifyOfPropertyChange(() => FitCommand);
        }
    }

在工具栏视图中,我简单地绑定到这个 属性:

<fluent:Button x:Name="FitButton" Command="{Binding FitCommand}" Header="Fit View"/>

之后,查看命令可分别用于每个详细视图。

但我不知道如何在没有访问 ZoomPanControl 源代码的情况下解决这个问题。