Search code examples
c#wpfxamlawesomiummahapps.metro

Binding Button to Boolean in WPF


I have a problem with a seemingly simple WPF application. I'm using MahApps.Metro's MetroWindow as my main Window which allows me to place buttons on the top of the window. Following their Getting Started example i have placed a few buttons on the top of the window. One of these buttons is a refresh button that allows a user to refresh the content of another control (Awesomium WebControl). What i would like to do is somehow bind the Refresh button to the WebControl's IsNavigating property (which is a boolean) so that the image on the button changes when the browser is navigating.

Here is the XAML i'm using for the button:

<Button x:Name="C_BTN_Refresh" Click="C_BTN_Refresh_Click">
    <StackPanel Orientation="Horizontal">
        <Rectangle Width="15" Height="15" Fill="{Binding Foreground, RelativeSource={RelativeSource AncestorType={x:Type Button}}}">
            <Rectangle.OpacityMask>
                <VisualBrush Stretch="Fill" Visual="{StaticResource appbar_refresh}" />
            </Rectangle.OpacityMask>
         </Rectangle>
     </StackPanel>
 </Button>

Keep in mind i'm very new to WPF.


Solution

  • You will need to create a converter like this:

    public class BoolVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (bool)value ? Visibility.Visible : Visibility.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Then include the converter as a resource in your view like this:

    <Window.Resources>
        <ResourceDictionary>
            <converters:BoolVisibilityConverter x:Key="BoolVisibilityConverter"/>
        </ResourceDictionary>
    </Window.Resources>
    

    Then use like this on your button:

    Visibility="{Binding Path=IsNavigating, Converter={StaticResource BoolVisibilityConverter}}"
    

    Hope this helps!