主/明细工具栏命令绑定

时间:2016-09-04 20:56:09

标签: wpf command toolbar master-detail

我有以下应用程序,其中包含工具栏,主列表和详细信息视图:

Overview

详细信息通过ContentControl“注入”。 详细信息包含UserControl,其中包含ScrollViewer等。在某些时候,有一个“ZoomPanControl”(不是我的)提供命令“FitView”。

我想从我的工具栏中为当前活动的详细信息视图执行命令“FitView”。

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

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

我无法弄清楚如何将工具栏按钮的命令属性绑定到当前活动的ZoomPanControl。在进行命令绑定时,我甚至都没有“看到”这个控件。

高度赞赏任何提示如何解决这个问题的提示。

2 个答案:

答案 0 :(得分:0)

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();

//命令CanExecute

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

答案 1 :(得分:0)

以下是我解决问题的方法。幸运的是,我可以访问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;

在我的应用程序的详细视图中,我将command-dependency-property绑定到我的ViewModel,如下所示:

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

重要的部分是Mode = OneWayToSource。这会将命令从ZoomPanControl“转发”到我的detail-viewmodel。

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

工具栏的viewmodel再次具有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的源代码。