我想突出显示(加粗并改变颜色)所有文本以组合框文本框的文本开头的项目。
我试图谷歌上面的问题,但我不幸得到任何类似的结果,这将解决我的问题。
我认为只是提示可能足以解决这个问题。虽然我是新手。如果有可能给我一个简单的例子。
更新:
以下是我尝试过的代码:
<ComboBox x:Name="cbUnder" ItemsSource="{Binding GroupsAndCorrespondingEffects}"
IsEditable="True" SelectedItem="{Binding SelectedGroup, Mode=TwoWay}"
TextSearch.TextPath="GroupName" Grid.Column="1" Grid.ColumnSpan="4" Grid.Row="3">
<ComboBox.ItemTemplate>
<DataTemplate>
<VirtualizingStackPanel Orientation="Horizontal">
<TextBlock Text="{Binding GroupName}" Width="250">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="Text" Value="ComboBox_PART_Editable">
<Setter Property="Foreground" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="{Binding CorrespondingEffect}" />
</VirtualizingStackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
但我不知道应该替换ComboBox_PART_Editable
我不想要整篇文章我只想使用Text.StartsWith
答案 0 :(得分:2)
我认为ComboBox
中的项目只是普通的string
值。您将不得不更改它并创建一个类来显示每个项目。这样做的原因是您需要一些bool
'flag'属性,您可以绑定到DataTrigger
,根据您的要求突出显示您的条目。所以你可以这样做:
public class CustomComboBoxItem : INotifyPropertyChanged
{
public string Value { get; set; } // Implement INotifyPropertyChanged correctly...
public bool IsHighlighted { get; set; } // ... here, unlike this example
}
然后,您需要在代码后面或视图模型中使用集合属性:
public ObservableCollection<CustomComboBoxItem> Items { get; set; }
同样,您必须在此正确实现INotifyPropertyChanged
接口。然后你可以将它绑定到ComboBox.ItemsSource
属性,如下所示:
<ComboBox ItemsSource="{Binding Items}" ... />
到目前为止,这应该看起来像带有文本条目的普通ComboBox
,所以我们必须提供DataTemplate
来告诉条目在满足条件时突出显示...这就是IsHighlighted
属性适用于:
<DataTemplate DataType="{x:Type YourXmlNamespacePrefix:CustomComboBoxItem}">
<TextBlock Text="{Binding Value}">
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsHighlighted}" Value="True">
<Setter Property="Background" Value="LightGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
最后一个难题是根据您的要求设置IsHighlighted
属性。为此,我们需要绑定到ComboBox.Text
属性,以便我们知道代码中的值。为此,在collection属性旁边添加另一个属性,并在更改时更新项目的IsHighlighted
属性:
public ObservableCollection<CustomComboBoxItem> Items { get; set; }
public string InputValue
{
get { return inputValue; }
set
{
inputValue = value;
NotifyPropertyChanged("Items");
for (int i = 0; i < Items.Count; i++)
{
Items[i].IsHighlighted = Items[i].StartsWith(inputValue);
}
}
}
...
<ComboBox ItemsSource="{Binding Items}" Text="{Binding InputValue}" ... />
那比我想要的要彻底,但你去了。让我知道你是怎么过的。