2012-02-27 62 views
0

我得到了一個具有幾個Canvas的UIElement,我想根據某些情況顯示或隱藏它。我希望在設計人員以及程序運行時看到這一點。我嘗試了幾個Bindings和BooleanToVisibilityConverter。但是我卡住了,找不到我的錯誤。因此,這裏的代碼:通過綁定設置元素的可見性

的UIElement(只有兩個帆布;我得到了在局部類的響應特性)

<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 - 其中顯示的是其中的Arrow - 已顯示。但他們都留Hidden。我也嘗試了一種不同的方法,直接在C#代碼中聲明LineVisibleArrowVisible屬性,但那也不起作用。有任何想法嗎?

回答

2

您的LineVisibleArrowVisible綁定沒有源設置,因此將使用DataContext作爲源。如果將根Canvas元素的DataContext設置爲用戶控件,您可以使自己的生活更輕鬆,從而可以省略所有重複的ElementName綁定,如described in this blog post I wrote

+0

太棒了!如果只有我在幾個小時之前發現了你的博客帖子。這正是我想要做的。一個問題,但:我必須輸入每個屬性作爲'字符串?我嘗試使用'Visibility',它給了我一個Exception,說明使用的類型不適合默認值類型。 – Nessuno 2012-02-27 12:48:28

+0

@Nessuno很高興幫助! ......「我是否必須將每個屬性鍵入字符串?」不,使用你需要的任何類型。您可以公開一個Visibility類型的屬性並將其綁定到UI。 – ColinE 2012-02-27 13:34:58

相關問題