我得到了一个带有几个Canvas的UIElement,我想根据某些情况显示或隐藏它。我想在设计器以及程序运行时看到这一点。我尝试了几个Bindings和BooleanToVisibilityConverter。但我被卡住了,无法找到我的错误。所以这是代码:
UIElement (只有两个Canvas;我在部分Class中获得了响应属性)
<component:AbstractComponent x:Class="View.LineComponent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:component="clr-namespace:View"
x:Name="userControl" Width="70" Height="10"
>
<component:AbstractComponent.Resources>
<BooleanToVisibilityConverter x:Key="VisibilityConverter" />
</component:AbstractComponent.Resources>
<Canvas Width="{Binding ElementName=userControl, Path=ActualWidth}">
<Canvas Name="Line"
Height="{Binding ElementName=userControl, Path=ActualHeight}"
Width="{Binding ElementName=userControl, Path=ActualWidth}"
Visibility="{Binding LineVisible, Converter={StaticResource VisibilityConverter}, FallbackValue=Hidden}"
>
<!-- Lot of stuff; Not interesting for the question-->
</Canvas>
<Canvas Name="Arrow"
Height="{Binding ElementName=userControl, Path=ActualHeight, TargetNullValue=6.397, FallbackValue=6.397}"
Width="{Binding ElementName=userControl, Path=ActualWidth, TargetNullValue=16.688, FallbackValue=16.688}"
Visibility ="{Binding ArrowVisible, Converter={StaticResource VisibilityConverter}, FallbackValue=Hidden}"
>
<!-- Lot of stuff; Not interesting for the question-->
</Canvas>
</Canvas>
</component:AbstractComponent>
在ParentWindow中使用
<component:LineComponent Height="50" Canvas.Top="100" Width="50" Canvas.Left="50" LineVisible="True"/>
<component:LineComponent Height="50" Canvas.Top="200" Width="50" Canvas.Left="50" ArrowVisible="True"/>
我希望在第一种情况下显示Line
- Canvas,而在另一种情况下显示Arrow
- 显示Canvas。他们都留下Hidden
。我还尝试了一种不同的方法,直接在C#-Code中声明LineVisible
和ArrowVisible
属性,但这两种方法都不起作用。有什么想法吗?
答案 0 :(得分:2)
您的LineVisible
和ArrowVisible
绑定没有源集,因此将使用DataContext
作为源。如果将根Canvas元素的DataContext
设置为用户控件,则允许您将所有重复的ElementName
绑定省略为described in this blog post I wrote,这将使您自己的生活更轻松。