【问题标题】:Binding one view datacontext to mainwindows datacontext将一个视图数据上下文绑定到主窗口数据上下文
【发布时间】:2016-02-09 12:37:26
【问题描述】:

我和我的朋友有一个有两个网格行的主窗口,每行应该代表一个不同的视图。顶视图是一个导航栏,我们希望根据您拥有的授权级别进行交换,从而能够访问不同的内容。

我们有一个视图位于另一个名为 OperatorNavView 的命名空间中,其中代码如下所示

<Grid>
    <StackPanel x:Name="NavBar" Orientation="Horizontal" Height="75" VerticalAlignment="Top" HorizontalAlignment="Stretch" Background="White" Grid.Row="0">
        <Button x:Name="btnTeams" Content="Lag"  Command="{Binding NavigationCommand}" CommandParameter="Team" HorizontalAlignment="Left" Width="77"  VerticalAlignment="Top" Background="#d87900" Height="44" />
        <Button x:Name="btnAchievements" Content="Utmärkelser" Command="{Binding NavigationCommand}" CommandParameter="Achievements" HorizontalAlignment="Left" VerticalAlignment="Top" Width="91" Background="#c20071" Height="44"/>
        <Button x:Name="btnNotifications" Content="Notifikations&#xD;&#xA;inställningar&#xD;&#xA;" Command="{Binding NavigationCommand}" CommandParameter="Notification" HorizontalAlignment="Left" Background="#95b800" VerticalAlignment="Top" Width="83" Height="44"/>
    </StackPanel>

命令上的绑定指的是主窗口视图模型“MainWindowViewModel”

我需要将主视图模型中的数据上下文连接到作为我的视图的 UserControl。我尝试过各种技术,例如在代码隐藏中编写

DataContext = new MainWindowViewModel();

这不起作用,我猜这是因为它是一个新实例并且没有显示更改。

用户控件上的按钮应该显示第二个视图。 MainWindow xaml 看起来像这样

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="75" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid Grid.Row="0">
        <ContentControl Content="{Binding CurrentNavBar}" />
        <Button x:Name="button" Command="{Binding AuthorizationCommand}" Content="hej" CommandParameter="Operator" HorizontalAlignment="Left" Margin="26,27,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
    <Grid Grid.Row="1">
        <ContentControl Content="{Binding CurrentViewModel}" />

    </Grid>

【问题讨论】:

  • 你尝试过相对源绑定吗?
  • 我还没试过。
  • 我无法让它工作,你有我的例子吗?我尝试在 ContentControl 的数据上下文设置上使用相对源绑定。

标签: c# wpf mvvm


【解决方案1】:

我在 Abhinav Sharma 建议的相对源绑定中找到了答案。 我以这种方式将 relativesource 绑定添加到 stackpanel 的 datacontext 中:

<StackPanel x:Name="NavBar" Orientation="Horizontal" Height="75" VertcalAlignment="Top" HorizontalAlignment="Stretch" Background="White" 
Grid.Row="0" DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext}" >

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2020-05-25
    • 2016-10-03
    • 2012-03-17
    • 2023-03-29
    • 1970-01-01
    • 2016-05-23
    相关资源
    最近更新 更多