WPF ComboBox - 不区分大小写的数据绑定

6
如果我正在数据绑定WPF组合框,是否有一种方法使绑定不区分大小写?
例如,如果组合框绑定到一个属性,其值为HELLO,能否选择值为Hello的组合框项?

你在什么情况下需要这个? - d.moncada
组合框绑定到集合,即主数据表和一些旧值,这些旧值存储在另一个表中,在那里我们将其绑定到一个属性,其值为HELLO。 - Sandy
2
我不能百分之百地说这是不可能的,但是反射是大小写敏感的(就像C#中的其他所有内容一样),所以这不起作用。 - BradleyDotNET
使用一个具有字符串属性的类填充它,并在该类上重写Equals()方法,以不区分大小写地比较字符串属性。 - 15ee8f99-57ff-4f92-890c-b56153
@BradleyDotNET 他想要大小写不敏感的值比较。该属性的名称不是 Hello;它的值是 "HELLO"。 - 15ee8f99-57ff-4f92-890c-b56153
3个回答

1
我通过实现IMultiValueConverter来完成这个任务。
该转换器应用于ComboBox上的ItemsSource绑定,并设置两个绑定。第一个是要选择的值,第二个绑定到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 中忽略大小写查找所选值,然后返回一个匹配的值。
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

0
在你的视图模型上创建一个新属性,将属性值转换为你想要的字符串形式。将你的 ComboBox(或其他 WPF 小部件)绑定到该属性。
例如:
public string NameOfValue
{
    get
    {
        return this.OtherProperty.ToCapitalizedString();
    }
}

通过这种方式,您可以控制属性值的格式化方式以便显示。但是,现在您需要向其他属性添加更改通知,以便当您更改OtherProperty的值时,数据绑定知道更新新属性的显示。

public string OtherProperty
{
    get { .. }
    set
    {
        Notify();
        Notify("NameOfValue");
    }
}

0
这是一个C#版本的@bkstill选定值忽略大小写转换器。
/// <summary>
/// Converts selected value to case ignore.
/// </summary>
/// <seealso cref="System.Windows.Data.IMultiValueConverter" />
public class SelectedValueIgnoreCaseConverter : IMultiValueConverter {
    /// <summary>
    /// Converts source values to a value for the binding target. The data binding engine calls this method when it propagates the values from source bindings to the binding target.
    /// </summary>
    /// <param name="values">The array of values that the source bindings in the <see cref="T:System.Windows.Data.MultiBinding" /> produces. The value <see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the source binding has no value to provide for conversion.</param>
    /// <param name="targetType">The type of the binding target property.</param>
    /// <param name="parameter">The converter parameter to use.</param>
    /// <param name="culture">The culture to use in the converter.</param>
    /// <returns>
    /// A converted value.If the method returns <see langword="null" />, the valid <see langword="null" /> value is used.A return value of <see cref="T:System.Windows.DependencyProperty" />.<see cref="F:System.Windows.DependencyProperty.UnsetValue" /> indicates that the converter did not produce a value, and that the binding will use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> if it is available, or else will use the default value.A return value of <see cref="T:System.Windows.Data.Binding" />.<see cref="F:System.Windows.Data.Binding.DoNothing" /> indicates that the binding does not transfer the value or use the <see cref="P:System.Windows.Data.BindingBase.FallbackValue" /> or the default value.
    /// </returns>
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
        if (typeof(string) != values[0].GetType()) {
            return null;
        }

        string selectedValue = values[0].ToString();

        ObservableCollection<string> options = (ObservableCollection<string>) values[1];

        if (selectedValue.IsNullOrEmpty()) {
            return null;
        }

        return options.FirstOrDefault(option => option.Equals(selectedValue, StringComparison.OrdinalIgnoreCase));
    }

    /// <summary>
    /// Converts a binding target value to the source binding values.
    /// </summary>
    /// <param name="value">The value that the binding target produces.</param>
    /// <param name="targetTypes">The array of types to convert to. The array length indicates the number and types of values that are suggested for the method to return.</param>
    /// <param name="parameter">The converter parameter to use.</param>
    /// <param name="culture">The culture to use in the converter.</param>
    /// <returns>
    /// An array of values that have been converted from the target value back to the source values.
    /// </returns>
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
        object[] result = new object[1];
        result[0] = value;
        return result;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接