C# WPF功能区上下文选项卡可见性绑定

C# WPF功能区上下文选项卡可见性绑定,c#,wpf,binding,ribboncontrolslibrary,C#,Wpf,Binding,Ribboncontrolslibrary,我发现很难找到绑定可视性的示例。我的代码中有一个属性,它应该决定何时显示功能区选项卡,但到目前为止我尝试的一切都没有效果。我的代码本质上是: public partial class MainWindow : RibbonWindow { public string Port { get; set; } } 下面是我的WPF代码的摘要。我正在寻找一种解决方案,将可见性属性绑定到主窗口。端口是否为null <ribbon:RibbonWindow ... xmlns

我发现很难找到绑定可视性的示例。我的代码中有一个属性,它应该决定何时显示功能区选项卡,但到目前为止我尝试的一切都没有效果。我的代码本质上是:

public partial class MainWindow : RibbonWindow
{
    public string Port { get; set; }
}
下面是我的WPF代码的摘要。我正在寻找一种解决方案,将
可见性
属性绑定到
主窗口。端口
是否为
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>

...
...

您可以创建一个转换器IsNotNullToVisibilityConverter

使用如下转换方法:

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;
    }
然后把它放在你的XAML里

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

这类似于我尝试过的东西,但我无法让它工作。我尝试在
Convert()
中放置一个
Console.WriteLine(“此处”)
,但没有打印任何内容。是否缺少其他内容?如果未调用Convert方法,则绑定可能不正确?您需要定义ElementName(端口属性所在的位置)尝试将RibbonWindow放在顶部x:Name=“ctl”,然后绑定:Visibility=“{binding Path=Port,ElementName=ctl,Converter={StaticResource IsNotNullToVisibilityConverter}”哦,等等,您的端口属性需要是要绑定的DependencyProperty,我更新了我的答案
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); }
    }