WPF将Ancestor对象绑定为CommandParameter

时间:2010-06-21 07:33:47

标签: c# wpf data-binding xaml mvvm

我有一个我要放大的自定义用户控件。我在MouseDoubleClick上测试了这个函数调用,它运行正常。 代码:

XAML
<cc:UserControl ItemsSource="{Binding Path=DataItem}" MouseDoubleClick="UserControl_MouseDoubleClick" />

CodeBehind c#
private void UserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    MainWindowViewModel.Instance.LightBoxCommand.Execute(sender);
}

现在我想用MVVM模式和这样的菜单来做:

XAML
<cc:UserControl ItemsSource="{Binding Path=DataItem}" MouseDoubleClick="UserControl_MouseDoubleClick" >
    <cc:UserControl.ContextMenu>
        <ContextMenu>
            <MenuItem Header="_Enlarge"
                      Command="{Binding Path=EnlargeCommand, RelativeSource={RelativeSource AncestorType={x:Type cc:UserControl}}}" CommandParameter="{Binding Path=.}"
                       />
            </MenuItem>
        </ContextMenu>
    </cc:UserControl.ContextMenu>
</cc:UserControl>

MVVM C#
private ICommand _enlargeCommand;
public ICommand EnlargeCommand
{
    get
    {
        if (_enlargeCommand == null)
            _enlargeCommand = new RelayCommand(n => {MainWindowViewModel.Instance.LightBoxCommand.Execute(n); });
        return _enlargeCommand;
    }
}

问题是我不太确定如何绑定到父对象,我想将整个UserControl发送到“LightBoxCommand”。有任何想法吗?

c#Lightboxcommand

public Visibility LightBoxVisible { get; set; }
public bool IsLightBoxVisible { get; set; }

public UserControl CurrentLightBoxItem { get; set; }

private ICommand _lightBoxCommand;
public ICommand LightBoxCommand
{
    get
    {
        if (_lightBoxCommand == null)
            _lightBoxCommand = new RelayCommand(n => {
                if (IsLightBoxVisible == true)
                    LightBoxVisible = Visibility.Hidden;
                else
                {
                    LightBoxVisible = Visibility.Visible;
                    CurrentLightBoxItem = ((UserControl)n).Copy();
                    NotifyPropertyChanged("CurrentLightBoxItem");
                }

                IsLightBoxVisible = !IsLightBoxVisible;
                NotifyPropertyChanged("LightBoxVisible");
            });
        return _lightBoxCommand;
    }
}

2 个答案:

答案 0 :(得分:1)

CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type cc:UserControl}}}"

答案 1 :(得分:0)

好的,我使用ElementSpy解决了它,看看elementSpy的工作原理如下:http://joshsmithonwpf.wordpress.com/2008/07/22/enable-elementname-bindings-with-elementspy/

和xaml:

    <cc:UserControl x:Name="UserControl" ItemsSource="{Binding Path=DataItem}" MouseDoubleClick="UserControl_MouseDoubleClick" >
        <cc:UserControl.ContextMenu>
            <ContextMenu local:ElementSpy.NameScopeSource="{StaticResource ElementSpy}">
                <MenuItem Header="_Enlarge" Command="{Binding Path=EnlargeCommand}" CommandParameter="{Binding ElementName=UserControl, Path=.}"/>
                </MenuItem>
            </ContextMenu>
        </cc:UserControl.ContextMenu>
    </cc:UserControl>