gpt4 book ai didi

c# - WPF ComboBox - 不区分大小写的数据绑定(bind)

转载 作者:太空狗 更新时间:2023-10-29 21:57:48 25 4
gpt4 key购买 nike

如果我对 WPF 组合框进行数据绑定(bind),有没有办法使绑定(bind)不区分大小写?

例如,如果组合框绑定(bind)了一个值为 HELLO 的属性,让它选择值为 Hello 的组合框项?

最佳答案

我通过实现 IMultiValueConverter 实现了这一点。

转换器应用于 ComboBox 上的 ItemsSource 绑定(bind)并设置两个绑定(bind)。第一个用于要选择的值。第二个绑定(bind)到 ComboBox 的 ItemsSource 属性,它是可能值的列表。

<ComboBox ItemsSource="{Binding Path=DataContext.EntityTypeOptions, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}">
<ComboBox.SelectedValue>
<MultiBinding Converter="{StaticResource SelectedValueIgnoreCaseConverter}">
<Binding Path="UpdatedValue" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged" />
<Binding Path="ItemsSource" Mode="OneWay" RelativeSource="{RelativeSource Mode=Self}" />
</MultiBinding>
</ComboBox.SelectedValue>
</ComboBox>

对于转换器,Convert() 方法在忽略大小写的 ItemsSource 中找到选定的值,然后从 ItemsSource 返回一个匹配的值。

ConvertBack() 方法只是将所选值放回到对象数组的第一个元素中。

Imports System.Globalization
Imports System.Windows.Data
Imports System.Collections.ObjectModel

Public Class SelectedValueIgnoreCaseConverter
Implements IMultiValueConverter

Public Function Convert(values() As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IMultiValueConverter.Convert
Dim selectedValue As String = TryCast(values(0), String)
Dim options As ObservableCollection(Of String) = TryCast(values(1), ObservableCollection(Of String))

If selectedValue Is Nothing Or options Is Nothing Then
Return Nothing
End If

options.Contains(selectedValue, StringComparer.OrdinalIgnoreCase)
Dim returnValue As String = Utilities.Conversions.ParseNullToString((From o In options Where String.Equals(selectedValue, o, StringComparison.OrdinalIgnoreCase)).FirstOrDefault)

Return returnValue
End Function

Public Function ConvertBack(value As Object, targetTypes() As Type, parameter As Object, culture As CultureInfo) As Object() Implements IMultiValueConverter.ConvertBack
Dim result(2) As Object
result(0) = value
Return result
End Function
End Class

关于c# - WPF ComboBox - 不区分大小写的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com