简体   繁体   中英

Converter to Bool

I have a normal Checkbox , where I want to set the IsChecked property to a Binding resource. The resource is a self written class myClass , which can be null or referenced (means not null ).

The Checkbox should be NOT checked, if the assigned object myObject (out of myClass ) is null
and checked, if it is not null .

What do I have to write in the IsChecked="..." property in my xaml file?

You can create a style with a DataTrigger that sets the IsChecked property.

<CheckBox>
   <CheckBox.Style>
      <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type CheckBox}}">
         <Setter Property="IsChecked" Value="True"/>
         <Style.Triggers>
            <DataTrigger Binding="{Binding MyObject}" Value="{x:Null}">
               <Setter Property="IsChecked" Value="False"/>
            </DataTrigger>
         </Style.Triggers>
      </Style>
   </CheckBox.Style>
</CheckBox>

An alternative is to create a reusable value converter.

public class NotNullToBooleanConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      return value != null;
   }

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

Create an instance of the converter in any resource dictionary, eg application resources.

<local:NotNullToBooleanConverter x:Key="NotNullToBooleanConverter"/>

This converter can be used directly in the binding.

<CheckBox IsChecked="{Binding MyObject, Converter={StaticResource NotNullToBooleanConverter}}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM