【发布时间】:2018-11-27 04:55:14
【问题描述】:
我正在与相对来源作斗争。我在选项卡项中,我想访问父模型视图。 如果项目是最后一个选项卡,目标是使某些上下文菜单项不可见。
视图模型:
public bool IsLastTab => ItemCollection.Count > 1;
xaml:
<Window x:Name="MainWinodw"
...
xmlns:ct="clr-namespace:ChromeTabs;assembly=ChromeTabs"
xmlns:vm="clr-namespace:Main.ViewModel"
xmlns:conv="clr-namespace:Main.Converters"
xmlns:ctConv="clr-namespace:ChromeTabs.Converters;assembly=ChromeTabs"
xmlns:usercontrols="clr-namespace:Main.UserControls"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
DataContext="{Binding Source={StaticResource Locator},Path=Main}" ">
<Window.Resources>
<conv:InverseBooleanToVisibilityConverter x:Key="InverseBooleanToVisibilityConverter" />
...
</Window.Resources >
<Grid>
<ct:ChromeTabControl x:Name="MyChromeTabControl"
TabPersistBehavior="Timed"
TabPersistDuration="0:0:0:5"
AddTabButtonBehavior="OpenNewTab"
Background="AliceBlue"
ItemsSource="{Binding ItemCollection}"
...">
...
<ct:ChromeTabControl.ItemTemplate>
<DataTemplate>
<Grid Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type ct:ChromeTabItem}}}">
...
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Close"
Command="{Binding Path=PlacementTarget.Tag.CloseTabCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
Visibility="{Binding IsLastTab,
RelativeSource={RelativeSource AncestorType={x:Type vm:ViewModelChromeTabs}},
Mode=OneWay,
Converter={StaticResource InverseBooleanToVisibilityConverter}}"
CommandTarget="{Binding Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" />
...
<Separator />
<MenuItem Header="{Binding IsPinned, Converter={StaticResource BooleanToPinTabTextConverter}}"
Command="{Binding Path=PlacementTarget.Tag.PinTabCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandTarget="{Binding Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"
CommandParameter="{Binding}" />
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</DataTemplate>
</ct:ChromeTabControl.ItemTemplate>
</ct:ChromeTabControl>
</Grid>
</Window>
当我将它放在项目类中时它正在工作,但我没有关于剩下多少个选项卡的信息,并且似乎在此实现一个信使的反逻辑。
【问题讨论】:
-
您的 ViewModel 可能不在 LogicalTree 中。您应该改为绑定到窗口的数据上下文:
{Binding DataContext.IsLastTab, RelativeSource={RelativeSource AncestorType={x:Type Window}} -
你好弗雷格,没有帮助。 Viewmodel 与
ItemsSource="{Binding ItemCollection}"一起工作,但在标签之后它只应用项目模型 -
那么是时候创建一个Minimal, Complete, and Verifiable example了。因为除了绑定不起作用之外,我没有其他线索。您还可以查看调试控制台是否有任何绑定表达式错误。
-
哦,我很愚蠢。
RelativeSource不起作用,因为ContextMenu不共享相同的 VisualTree。请参阅stackoverflow.com/questions/3583507/… 了解更多信息 -
谢谢,这正是我的问题。之前没找到这个。我试试这个