You could create a converter that returns a Visibility
for certain keywords. In XAML you can pass a list of keywords in XAML that will return Visibility.Visible
, otherwise it will be Visibility.Hidden
.
public class KeywordToVisibilityConverter : IValueConverter
{
public List<string> Keywords { get; }
public KeywordToVisibilityConverter()
{
Keywords = new List<string>();
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is string keyword
? Keywords.Contains(keyword) ? Visibility.Visible : Visibility.Hidden
: Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException();
}
}
Create an instance of the converter in a resource dictionary in scope, e.g. TreeView.Resources
.
<TreeView.Resources>
<local:KeywordToVisibilityConverter x:Key="KeywordToVisibilityConverter">
<local:KeywordToVisibilityConverter.Keywords>
<system:String>type</system:String>
<system:String>class</system:String>
<system:String>subclass</system:String>
</local:KeywordToVisibilityConverter.Keywords>
</local:KeywordToVisibilityConverter>
</TreeView.Resources>
Do not forget to add the XML namespace for system
.
xmlns:system="clr-namespace:System;assembly=System.Runtime"
for .NET Core
xmlns:system="clr-namespace:System;assembly=mscorlib"
for .NET Framework
Then, use the converter to set the visibility of the TextBlock
depending on Tag
.
<TextBlock Visibility="{Binding SelectedItem.Tag, ElementName=treeView, Converter={StaticResource KeywordToVisibilityConverter}}">
<Run Text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
<Run Text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>
A converter for your second case is fairly easier, as it just checks the type (no namespace or list needed).
public class IsGuidToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is Guid ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException();
}
}
As before, create an instance in XAML and use it to bind the Visibility
of TextBlock
.
As a note, if you wanted to bind the allowed keywords, too, the you would have to create a IMultiValueConverter
used in a MultiBinding
in XAML. If you want the TextBlock
not only hidden, but removed leaving empty space, replace Hidden
with Collapsed
. Finally, to state the obvious: Be careful, the approaches are not equivalent. Depending on the possible Tag
values they may lead to different results.