Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 386
Sturm Avatar asked Jul 19 '26 18:07

Sturm


2 Answers

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).

like image 74
kmatyaszek Avatar answered Jul 22 '26 08:07

kmatyaszek


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;
    }
}
like image 43
Agustin Meriles Avatar answered Jul 22 '26 09:07

Agustin Meriles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!