WinUI3 ComboBox: How to show one property of Items when DropDown is open and a different one when DropDown is closed
See the question and my original answer on StackOverflowHere is one solution mostly based on XAML and databinding with the x:Bind extension (I've used a UserControl
to be able to put the converter resource somewhere because with WinUI3 you can't put it under the Window
element):
<UserControl
x:Class="MyApp.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:classes="using:MyApp.Models">
<UserControl.Resources>
<classes:VisibilityNegateConverter x:Key="vn" />
</UserControl.Resources>
<ComboBox x:Name="TheComboBox" ItemsSource="{x:Bind classes:FooBar.FooBars}">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="classes:FooBar">
<StackPanel>
<TextBlock Text="{x:Bind Foo}" Visibility="{x:Bind TheComboBox.IsDropDownOpen}" />
<TextBlock Text="{x:Bind Bar}" Visibility="{x:Bind TheComboBox.IsDropDownOpen, Converter={StaticResource vn}}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</UserControl>
And the converter for the "reverse" visibility conversion between Boolean
and Visibility
("forward" conversion is now implicit in WinUI3 and UPW for some times)
public class VisibilityNegateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language) => (bool)value ? Visibility.Collapsed : Visibility.Visible;
public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotSupportedException();
}
Note: I've tried to use function binding to avoid the need for a converter, something like this:
<TextBlock Text="{x:Bind Bar}" Visibility="{x:Bind TheComboBox.IsDropDownOpen.Equals(x:False)}" />
But compilation fails miserably (maybe a bug in XAML compiler?)