c# - WPF MVVM 绑定相对源
问题描述
我正在与相对来源作斗争。我在选项卡项中,我想访问父模型视图。如果项目是最后一个选项卡,目标是使某些上下文菜单项不可见。
视图模型:
public bool IsLastTab => ItemCollection.Count > 1;
xml:
<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>
当我将它放在项目类中时它正在工作,但是我没有关于剩下多少个选项卡的信息,并且似乎在此实现一个信使的反逻辑。
解决方案
你已经这样定义IsLastTab
了:
public bool IsLastTab => ItemCollection.Count > 1;
这似乎不能确定当前选项卡是否是最后一个选项卡。
你需要这样的东西:
public bool IsLastTab => ReferenceEquals(this, ItemCollection.LastOrDefault());
(由于您没有发布底层视图模型,这只是一个猜测。确切的代码可能会改变。)
而且,您还需要调用InotifyPropertyChanged.propertychanged在每个选项卡集合更改时为每个标签项目的属性“ IslastTab”派出。
推荐阅读
- docusignapi - DocuSignapi - OAuth API 调用被计为 API 请求,其数量有限制
- javascript - Angular 2中的每个按键都没有调用自定义验证器
- c++ - Qt异步调用:异步调用完成后如何运行
- c - 此函数声明中是否存在语法错误?
- python - 在子文件夹中使用 .gitignore 和 *.pyc
- python - 运行程序时输入错误
- octopus-deploy - 如何在八达通服务器上运行与脚本任务步骤相同的“部署包步骤”
- jquery - 如果 li 在 ajax 加载的内容中有 ul
- python - KeyError:“日期”我使用 set_index 错了吗?
- android - 如何在Android中的表格布局中设置表格行中心水平