将选中的togglebutton状态绑定到usercontrol的可见性

时间:2013-09-20 19:10:16

标签: c# wpf xaml

我现在有办法使用代码隐藏和更改'面板'的可见性,但我想知道这是否可以直接的xaml方式完成?

2 个答案:

答案 0 :(得分:3)

您应该可以使用ElementName以及将{/ 1}}转换为可见性的IValueConverter来绑定它:

<Grid>
    <Grid.Resources>
        <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
    </Grid.Resources>
    <UserControl Visibility="{Binding ElementName=toggle,
                                      Path=IsChecked,
                                      Converter={StaticResource BoolToVisibilityConverter}}" 
    />
    <ToggleButton x:Name="toggle" />
</Grid>

转换器:

public class BoolToVisibilityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var isChecked = (bool)value;
        return isChecked ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

答案 1 :(得分:1)

您可以在此处执行以下操作..您可以将usercontroltogglebutton作为父Contentcontrol的内容,并使用DataTemplate触发器设置可见性用户控制取决于ToggleButton

的已检查状态
       <ContentControl>
            <ContentControl.ContentTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <local:myusercontrol  x:Name="control"/>

                        <ToggleButton Content="click" x:Name="toggleBtn"/>
                    </StackPanel>
                    <DataTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="false"  SourceName="toggleBtn">
                            <Setter Property="Visibility" Value="Visible" TargetName="control"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="true" SourceName="toggleBtn">
                            <Setter Property="Visibility" Value="Collapsed" TargetName="control"/>
                        </Trigger>
                    </DataTemplate.Triggers>
                </DataTemplate>
            </ContentControl.ContentTemplate>
        </ContentControl>