ValueConverter for Unchecked CheckBox

时间:2018-03-19 09:14:25

标签: c# wpf xaml

我需要在选中CheckBox时加载一个项目,如果选中它,它应该会消失,因为还会加载其他内容。

在这种情况下,我在哪里犯了错误?

XAML:

    <StackPanel> 
      <StackPanel.Resources>
        <vm:NegatingConverter x:Key="NegatingConverter"/> 
      </StackPanel.Resources>

        <CheckBox Content="Load?" Name="LoadsDifferent"/>

        <StackPanel Height="15" Width="360" Visibility="{Binding ElementName=LoadsDifferent, Path=IsChecked, Converter={StaticResource NegatingConverter}}">
           <TextBlock>Load line<Run BaselineAlignment="Subscript" FontSize="10">k</Run> [kN/m]</TextBlock>
        </StackPanel>
    </StackPanel>

NegatingConverter

[ValueConversion(typeof(bool), typeof(bool))]
    public class NegatingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !((bool)value);
        }

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

2 个答案:

答案 0 :(得分:1)

您将bool值绑定到Visibility,这将导致绑定失败。由于Visibility的默认值为Visible,您将看不到任何更改。

以下是您可能会觉得有用的NegatedBooleanToVisibilityConverter

public class NegatedBooleanToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var flag = false;

        if (value is bool)
        {
            flag = !(bool)value;
        }

        if (parameter != null)
        {
            return flag ? Visibility.Visible : Visibility.Hidden;
        }

        return flag ? Visibility.Visible : Visibility.Collapsed;
    }

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

答案 1 :(得分:1)

根据我的评论,对于UI级别的操作,您应该始终更喜欢Xaml脚本来提高性能。当您在WPF中使用强大的触发器时,无需实现转换器。

您的请求可以使用触发器轻松实现,如下所述。

  <StackPanel>

        <CheckBox Content="Load?" Name="LoadsDifferent"/>

        <StackPanel Height="15" Width="360" >
            <StackPanel.Style>
                <Style TargetType="StackPanel">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=LoadsDifferent, Path=IsChecked}" Value="true">
                            <Setter Property="Visibility" Value="Hidden"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ElementName=LoadsDifferent, Path=IsChecked}" Value="false">
                            <Setter Property="Visibility" Value="Visible"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </StackPanel.Style>
            <TextBlock>Load line<Run BaselineAlignment="Subscript" FontSize="10">k</Run> [kN/m]</TextBlock>
        </StackPanel>
    </StackPanel>