Search code examples
c#wpfbindingribboncontrolslibrary

WPF Ribbon Contextual Tab Visibility binding


I am finding it surprisingly hard to find examples of binding the visibility of a RibbonContextualTabGroup. I have a property in my code-behind that should decide when to display a ribbon tab, but everything I've tried so far has no effect. My code-behind is essentially:

public partial class MainWindow : RibbonWindow
{
    public string Port { get; set; }
}

A summary of my WPF code is below. I'm looking for a solution that binds the Visibility property to whether or not MainWindow.Port is null.

<ribbon:RibbonWindow
    ...
    xmlns:src="clr-namespace:MagExplorer" />

    ...

    <ribbon:RibbonTab x:Name="COMTab" 
                      Header="COM"
                      ContextualTabGroupHeader="Communications">
    ...
    </ribbon:RibbonTab>

    <ribbon:Ribbon.ContextualTabGroups>
        <ribbon:RibbonContextualTabGroup Header="Communications"
                                         Visibility="<What goes here?>" />
    </ribbon:Ribbon.ContextualTabGroups>

Solution

  • You can create a Converter IsNotNullToVisibilityConverter

    with the Convert method like this:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
            {
                if (!string.IsNullOrEmpty((string)value))
                    return Visibility.Visible;
            }
            else if (value != null)
            {
                return Visibility.Visible;
            }
    
            return Visibility.Collapsed;
        }
    

    And then put it in your XAML

    <Window.Resources>
        <IsNotNullToVisibilityConverter x:Key="IsNotNullToVisibilityConverter" />
    </Window.Resources>
    ...
    Visibility="{Binding Path=Port, Converter={StaticResource IsNotNullToVisibilityConverter}}" 
    

    In your code behind:

    public static readonly DependencyProperty PortProperty =
            DependencyProperty.Register
            ("Port", typeof(String), typeof(NameOfYourClass),
            new PropertyMetadata(String.Empty));
    
    public String Port
        {
            get { return (String)GetValue(PortProperty); }
            set { SetValue(PortProperty, value); }
        }