我正在使用WPF Prism.Mvvm。 我在侧面有一个导航栏,其中包含一个绑定到Itemssource的Listview。这些项目包含图像和内容。现在,我的目标是折叠项目的内容,以便导航控件仅显示图标。
我已经定义了一个Visibility绑定,在我的Listview之外的某些图像上使用了此绑定,效果很好。但是,一旦我尝试对Listview的itemtemplate中的任何内容使用确切的绑定,就什么也没有发生。 有趣的是,如果我将“可见性”设置为“不折叠”而没有约束,那么它将再次起作用。
这是我的视图
<UserControl.Resources>
<ResourceDictionary>
<BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
</ResourceDictionary>
[...]
<DockPanel >
<ContentControl DockPanel.Dock="Top">
<StackPanel>
<Button Margin="5,5,5,5" Style="{StaticResource MyButton}" Command="{Binding ExpandMenuCommand}" Content="Menu" HorizontalAlignment="Left" Width="43.017" />
<ListView BorderThickness="0" VerticalContentAlignment="Top" SelectionMode="Single" ItemsSource="{Binding MenuItems}" SelectedItem="{Binding SelectedItem}" Background="Transparent">
<ListView.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Margin="0,10,0,10" Grid.Column="0" Source="{Binding ImageSource}" />
<TextBlock Visibility="{Binding Visibility, Converter={StaticResource booleanToVisibilityConverter}}" VerticalAlignment="Center" Margin="10,10,10,10" Grid.Column="1" Text="{Binding Content}" Background="Transparent" FontFamily="Arial" FontWeight="Bold" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</ContentControl>
<ContentControl DockPanel.Dock="Bottom">
<Grid>
<Image Visibility="{Binding Visibility, Converter={StaticResource booleanToVisibilityConverter}}" HorizontalAlignment="Center" Height="59" Margin="19,0,0,25" Width="182" Source="/ModuleA;component/Images/Logo.png" VerticalAlignment="Bottom" />
</Grid>
</ContentControl>
</DockPanel>
现在,如果我将Visibility="{Binding Visibility, Converter={StaticResource booleanToVisibilityConverter}}"
复制到该Itemtemplate上方的任何内容(例如Listview本身或Stackpanel),则其工作方式类似于Listview下的Image。但Listview.ItemTemplate中的Textblock,Image或Grid本身不会响应我的绑定。将其设置为Visibility="Collapsed"
就像我打算的那样工作。
我的视图模型:
private static bool _expanded = true;
private bool _visibility = _expanded;
public bool Visibility
{
get { return _visibility; }
set { SetProperty(ref _visibility, value); }
}
private void ExpandMenu()
{
_expanded = !_expanded;
Visibility = _expanded;
}
答案 0 :(得分:1)
ListView.ItemTemplate是MenuItem对象的模板。我想Visibility
不是MenuItem类的属性,它属于另一个视图模型。因此,您需要从其他DataContext绑定它:
<TextBlock Visibility="{Binding DataContext.Visibility,
Converter={StaticResource booleanToVisibilityConverter},
RelativeSource={RelativeSource AncestorType=ListView}}"
VerticalAlignment="Center"
Margin="10,10,10,10" Grid.Column="1"
Text="{Binding Content}"
Background="Transparent"
FontFamily="Arial"
FontWeight="Bold" />