Sturm
Sturm

Reputation: 4125

ToggleButton Content binding to its state

I need exactly was is solved in this question, unfortunately it is for Silverlight and I was not able to make that "Interactivity" libraries to work.

I have a ToggleButton and I want to change the Content property to "Hello" when it's checked "Good bye" when it's unchecked. Changing it manually is not an option for me in this case, as the change of the state can be done from multiple sources.

I think that an Converter might be needed for this task, and I've seen converters to Visibility but not to string.

EDIT: I've thought about putting both words in a stackpanel and switch the visibility Visible/Collapsed bound to the state:

         <ToggleButton.Content>
          <StackPanel>
              <TextBlock Text="Hello" Visibility="{Binding ...}"/>
              <TextBlock Text="GoodBye"/>
          </StackPanel>
      </ToggleButton.Content>

Upvotes: 2

Views: 4885

Answers (2)

kmatyaszek
kmatyaszek

Reputation: 19296

You can use Triggers:

<ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="ToggleButton">
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="Hello" />
                </Trigger>
                <Trigger Property="IsChecked" Value="False">
                    <Setter Property="Content" Value="Good bye" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

If you want to use System.Windows.Interactivity.dll you can find it in Microsoft Expression Blend Software Development Kit (SDK) (download link).

Upvotes: 8

Agustin Meriles
Agustin Meriles

Reputation: 4854

You could implement a BooleanToSalutation:

public class BooleanToSalutationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Boolean)
        {
            return (bool)value ? "Hello" : "Good bye";
        }

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is string)
        {
            return ((string)value) == "Hello";
        }

        return value;
    }
}

Upvotes: 2

Related Questions