WPF MVVM 绑定相对源



我正在为相对来源而苦苦挣扎。我在选项卡项内,我想访问父模型视图。 目标是使某些上下文菜单项不可见(如果该项是最后一个选项卡(。

视图模型:

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>

当我把它放在 Item 类中时,它正在工作,但我没有关于还剩多少个选项卡的信息,在这里为此实现一个信使似乎是反逻辑的。

您已经定义了这样的IsLastTab

public bool IsLastTab => ItemCollection.Count > 1;

这似乎并不能确定当前选项卡是否是最后一个选项卡。

你需要这样的东西:

public bool IsLastTab => ReferenceEquals(this, ItemCollection.LastOrDefault());

(由于您没有发布基础视图模型,因此这只是一个猜测。确切的代码可能会更改。

并且,每当选项卡集合更改时,您还需要为每个选项卡项的属性"IsLastTab"调用INotifyPropertyChanged.PropertyChanged。

最新更新