如果我正在编写WPF组合框,是否有办法使绑定不区分大小写?
例如,如果组合框绑定到值为HELLO的属性,是否选择值为Hello的组合框项?
答案 0 :(得分: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忽略大小写中找到所选值,然后从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
答案 1 :(得分:0)
在视图模型上创建一个新属性,该属性提供以所需格式转换为字符串的属性值。将您的ComboBox(或其他WPF小部件)绑定到该属性。
例如:
public string OtherProperty
{
get { .. }
set
{
Notify();
Notify("NameOfValue");
}
}
通过这种方式,您可以精确控制属性值的格式化以显示它。但是,现在您必须向其他属性添加更改通知,以便在更改OtherProperty的值时,数据绑定知道更新新属性的显示。
{{1}}