WPF使用切换按钮切换画布或画布线可见性

时间:2014-04-23 12:57:45

标签: wpf canvas toggle visibility

我需要将画布可见性从可见切换到隐藏。如果我可以手动更改画布'visibility =“hidden”并运行程序并且画布消失了,那么我认为我可以用按钮切换它。这是我到目前为止所拥有的。任何帮助,将不胜感激。

XAML                                     

    <Canvas Background="Transparent" Height="200" HorizontalAlignment="Left" Margin="169.5,132.5,0,0" Name="Canvas1" VerticalAlignment="Top" Width="200" Visibility="Visible">
        <Line X1="100" Y1="0" X2="100" Y2="75" Stroke="Red" StrokeThickness="0.95" />
        <!--Top long vertical line> /-->
        <Line X1="100" Y1="95" X2="100" Y2="105" Stroke="Red" StrokeThickness="0.95" />
        <!--Crosshair vertical line> /-->
        <Line X1="100" Y1="125" X2="100" Y2="200" Stroke="Red" StrokeThickness="0.95" />
        <!--Bottom long vertical line> /-->
        <Line X1="0" Y1="100" X2="75" Y2="100" Stroke="Red" StrokeThickness="0.75" />
        <!--Left long horizontal line> /-->
        <Line X1="95" Y1="100" X2="105" Y2="100" Stroke="Red" StrokeThickness="0.75" />
        <!--Crosshair horizontal line> /-->
        <Line X1="125" Y1="100" X2="200" Y2="100" Stroke="Red" StrokeThickness="0.75" />
        <!--Right long horizontal line> /-->
        <!--Ellipse
  Canvas.Top="50"
  Canvas.Left="50"
  Height="100"
  Width="100"
  StrokeThickness="0.75"
  Stroke="Red"/-->
    </Canvas>
    <Canvas Height="73" HorizontalAlignment="Right" Name="Canvas2" VerticalAlignment="Top" Width="69">
        <Image Height="56" Name="Image1" Stretch="Fill" Width="48" Canvas.Left="7" Canvas.Top="8" Source="/HornetView;component/Images/imageedit_6_2746796678.png" />
    </Canvas>
</Grid>
</Window>

VB

Public Sub Button1_Checked_1(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Checked
    Dim chkstat As Integer
    chkstat = 0
    If Button1.IsChecked = True And chkstat = 0 Then
        Canvas1.Visibility = Windows.Visibility.Visible
        chkstat = 1
    Else
        Canvas1.Visibility = Windows.Visibility.Hidden
    End If

End Sub

2 个答案:

答案 0 :(得分:4)

使用BooleanToVisibilityConverter并将ToggleButton.IsChecked绑定到Canvas.Visibility

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>

...

<Canvas Name="Canvas1" Visibility="{Binding IsChecked, ElementName=Button1, Converter={StaticResource BooleanToVisibilityConverter}}">
    ...
</Canvas>

答案 1 :(得分:1)

在类中的其他位置定义checkstat,而不是在togglebuttonbutton检查方法中定义。在您的代码中,您指定的值为'o;每次检查togglebutton按钮时检查状态,以便它永远不会进入“其他”部分。

使用booltovisibility转换器继续使用上述解决方案,这应该可以解决您的问题,而不是在代码中使用私有对象