I have a window with a DataGrid that I want to hide certain columns based on the contents of the ObservableCollection that is the ItemSource for the DataGrid.
Based on this question: Conditional element in xaml depending on the binding content
I wrote a VisibilityConverter:
public class StringLengthVisiblityConverter : IValueConverter
{
public StringLengthVisiblityConverter() { }
public Object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.ToString().Length == 0)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
}
public Object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Here is the XAML:
<DataGrid.Resources>
<local:StringLengthVisiblityConverter x:Key="VisConverter"/>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Switch Port" Binding="{Binding FCPort}"/>
<DataGridTextColumn Width="*" Header="WWPN" Binding="{Binding Path=WWPN}"
Visibility="{Binding Path=WWPN, Converter={StaticResource VisConverter}}"/>
<DataGridTextColumn Header="FCID" Binding="{Binding Path=FCID}"
Visibility="{Binding Path=FCID, Converter={StaticResource VisConverter}}"/>
</DataGrid.Columns>
</DataGrid>
I loaded the collection with instances of a class where the WWPN and FCID are both null. I expected those columns to be hidden in the datagrid, but they were still visible. I added a breakpoint to the VisbilityConverter and ran it through a debugger but it doesn't look like it's getting called.