问题
In a ComboBox, we can jump to an item by typing its first few letters. This is when IsTextSearchEnabled
property is set, which by default is true.
I have a custom ComboBox with images in the beginning, followed by a short text.
icon1 + Violet
icon2 + Red
icon3 + Blue
If I type "r", I expect to navigate to the Red
item in the dropdown. However, because of an icon in the beginning, the IsTextSearchEnabled
property does not behave as expected.
How can I make this work?
For example, in MyDropdown.cpp
, I have
MyDropDownItem^ comboItem = ref new MyDropDownItem(icon, title);
sourceItems->Append(comboItem);
sourceItems
is the list of items that the ItemsSource of this control uses. Each combobox item has a different image(icon) and hence, image src cannot be statically defined in xaml template.
回答1:
How to make isTextEnabled property work in case of ComboBox with icons in the beginning of text?
You could bind ComboBox ItemsSource
with string collection then custom the item content like the following, when you typing text, it will match with ItemsSource
.
<ComboBox
x:Name="MyComboBox"
Width="200"
Header="Colors"
IsEditable="True"
Loaded="ComboBox_Loaded"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image
Width="22"
Height="22"
Source="Assets/StoreLogo.png"
/>
<TextBlock
Margin="10"
Text="{Binding}"
TextAlignment="Center"
/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
MyComboBox.ItemsSource = new List<string>() { "Red", "Green", "Blue" };
}
Update
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string resaut = string.Empty;
switch (value.ToString())
{
case "Blue":
resaut = "ms-appx:///Assets/BlueImage.png";
break;
case "Green":
resaut = "ms-appx:///Assets/GreenImage.png";
break;
case "Red":
resaut = "ms-appx:///Assets/RedImage.png";
break;
default:
break;
}
return resaut;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Usage
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image
Width="22"
Height="22"
Source="{Binding Converter={StaticResource ImageConverter}}"
/>
<TextBlock
Margin="10"
Text="{Binding}"
TextAlignment="Center"
/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
来源:https://stackoverflow.com/questions/59261183/how-to-make-istextsearchenabled-property-work-in-case-of-combobox-with-icons-in