Showing posts with label XAML. Show all posts
Showing posts with label XAML. Show all posts

Tuesday, July 13, 2010

NullToBoolValueConverter for WPF

  You can enable or disable WPF elements based on if they are null or not. This is not supported, but you can create a simple value converter.
  /// <summary>
  /// Converts null to boolean.
  /// </summary>
  /// <remarks>
  /// If parameter is not specified or specified with null:
  /// if passed value is null then true is returned, otherwise false.
  /// If parameter is specified then inversion is done:
  /// if passed value is null then false is returned, otherwise true.
  /// </remarks>
  [ValueConversion(typeof(object), typeof(bool))]
  public class NullToBoolValueConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      bool result = value == null ? true : false;
      if (parameter != null)
        return !result;
      return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      return value;
    }
  }


  This value converter allows me to bind to any property taking a boolean argument with the following syntax in XAML.
<local:NullToBoolValueConverter x:Key="NullToBoolValueConverter"/>

<ComboBox.IsEnabled>
  <Binding ElementName="TetsComboBox" Path="SelectedItem" Converter="{StaticResource NullToBoolValueConverter}" ConverterParameter="true" />
</ComboBox.IsEnabled>

Friday, April 2, 2010

WPF show or hide element based on CheckBox

  Today I had to do the task for showing or hiding elements based the value of a checkbox. In WinForms 2.0 for this purpose it was necessary to subscribe to event CheckedChanged and in his handler write the code:

private void myCheckBox_CheckedChanged(object sender, EventArgs e)
{
  myTextBox.Visible = myCheckBox.Checked;
}

  With the new Visibility Enum in WPF, this becomes a bit trickier. To accomplish this, you can use converter BooleanToVisibilityConverter that accept a boolean value and return a visibility value. Now we can cleanly show or hide an element based on a checkbox using just XAML code. The XAML code to use this is below:

<Window
  x:Class="MyTest.XamlOnly"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="XamlOnly" Height="300" Width="300">

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

  <StackPanel Orientation="Vertical">
    <CheckBox Content="Check to show text box below me" Name="checkViewTextBox"/>
    <TextBox Text="only seen when above checkbox is checked" Visibility="{Binding Path=IsChecked, ElementName=checkViewTextBox, Converter={StaticResource BoolToVisConverter}}"/>
  </StackPanel>

</Window>