使用RelativeSource绑定到ViewModel不起作用

时间:2016-01-12 15:21:45

标签: c# wpf xaml data-binding relativesource

我的应用程序有一个导航菜单,使用命令从一个页面到另一个页面。

导航菜单已在Xaml中创建,我将其存储在Navigation.xaml中,见下文

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Cirdan.Wpf.Navigation"
xmlns:infrastructure="clr-namespace:Cirdan.Wpf.Infrastructure">

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Cirdan.Wpf;component/Resources/Styles/Stylesheet.xaml" />
</ResourceDictionary.MergedDictionaries>

<DataTemplate x:Key="Navigation" >        
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="4*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <UniformGrid Grid.Row="0" Columns="1">
            <Button DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:NavigationViewModelBase}}}" Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Command="{Binding ViewerPageCmd}" >Viewer Screen</Button>
            <Button DataContext="{Binding NavigationViewModel, Source={x:Static infrastructure:MainWindow.LocatorX}}" Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Command="{Binding}" >Acquisition Screen</Button>
            <Button DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:NavigationViewModelBase}}}" Visibility="{Binding ElementName=Menu, Path=IsChecked, Converter={StaticResource VisibilityConverter}}" Command="{Binding WorklistPageCmd}" >Worklist Screen</Button>
        </UniformGrid>
        <ToggleButton Grid.Row="1" Style="{StaticResource ToggleBtnToolStyle}" x:Name="Menu" IsChecked="true" Background="Transparent" BorderThickness="0" >
            <StackPanel Orientation="Horizontal">
                <ContentPresenter Margin="5" Height="50" Content="{StaticResource MenuIcon}"></ContentPresenter>
                <Viewbox>
                    <TextBlock Margin="5" Style="{StaticResource TxtToolStyle}">Menu</TextBlock>
                </Viewbox>
            </StackPanel>
        </ToggleButton>
    </Grid>
</DataTemplate>

我试图将这些按钮命令绑定到的ViewModel称为NavigationViewModelBase.cs

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;

namespace Cirdan.Wpf.Navigation
{
public abstract class NavigationViewModelBase : ViewModelBase
{
    private List<DicomMetadataModel> _dicomMetadata;

    //Navigation Cmd
    public ICommand AcquisitionPageCmd { get; private set; }
    public ICommand ManualEntryWindowCmd { get; private set; }
    public ICommand SessionWindowCmd { get; private set; }
    public ICommand SettingsWindowCmd { get; private set; }
    public ICommand StudyInfoPageCommandCmd { get; private set; }
    public ICommand ViewerPageCmd { get; private set; }
    public ICommand WorklistPageCmd { get; private set; }


    protected NavigationViewModelBase()
    {
        AcquisitionPageCmd = new RelayCommand(() => Messenger.Default.Send(new GoToPageMessage(Pages.AcquisitionScreen)));
        ManualEntryWindowCmd = new RelayCommand(() => Messenger.Default.Send(new ShowDialogMessage(Pages.ManualEntry, DicomMetadata)));
        SessionWindowCmd = new RelayCommand(() => Messenger.Default.Send(new ShowDialogMessage(Pages.Session)));
        SettingsWindowCmd = new RelayCommand(() => Messenger.Default.Send(new ShowDialogMessage(Pages.Settings)));
        ViewerPageCmd = new RelayCommand(() => Messenger.Default.Send(new GoToPageMessage(Pages.Viewer)));
        WorklistPageCmd = new RelayCommand(() => Messenger.Default.Send(new GoToPageMessage(Pages.Worklist)));
    }
}
}

然后在每个页面上使用以下代码添加导航

<ContentControl Grid.Column="2" Grid.Row="2" ContentTemplate="{StaticResource Navigation }" />

目前我没有收到任何错误,当我在上面的一个按钮中设置DataContext时,当我去绑定我的命令时,我可以看到该Viewmodel的所有属性,所以该位是工作正常,但是当我运行程序并单击这些按钮时,没有任何事情发生。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

RelativeSource FindAncestor在VisualTree中查找祖先。

VisualTree可能如下所示:

Window
   Grid
      TextBlock
      TextBox
      Button

ViewModel不在视觉三

例如,Button的祖先就是Grid和Window。

如何做呢?

好吧,在ResourceDictionary中使用ContentTemplate创建自定义UserControl而不是ContentControl。

在usercontrol中将DataContext设置为继承自NavigationViewModelBase的类。

然后绑定将很简单:

    <UniformGrid Grid.Row="0" Columns="1">
        <Button Command="{Binding ViewerPageCmd}">Viewer Screen</Button>
        <Button Command="{Binding AcquisitionPageCmd}">Acquisition Screen</Button>
        <Button Command="{Binding WorklistPageCmd}" >Worklist Screen</Button>
    </UniformGrid>

答案 1 :(得分:1)

Ancestor Binding仅适用于visualtree / view中的元素,或仅适用于页面中的元素。 viewModel不是页面中的任何位置作为控件。因此,取代viewModel给出具有 NavigationViewModelBase 作为datacontext.write绑定的视图类型如下所示(如果您的视图/控件是 NavigationView ,则绑定将是)。并在路径中写入 vm:NavigationViewModelBase 的属性 class:

<Button DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type v:NavigationView}}, path= PropertyYouWantToBind}"

只要确保你没有为层次结构中的任何其他控件定义DataContext,Button将获得与视图相同的DataContext,然后你只需要绑定命令。你已经正确完成了。

如果您没有将DataContext提供给视图中的任何控件,那么只需将其提供给contentControl或Grid即可。只需

<Grid>
  <Grid.DataContext>
      <vm:NavigationViewModelBase />
  </Grid.DataContext>
<Grid.RowDef.......

然后使用简单绑定命令。