为什么WPF组合框项目源转换器获取整个集合而不是项目?

时间:2016-01-10 10:29:02

标签: c# wpf data-binding

当我使用以下实现进行调试时。 Convert-method参数值具有所有值,当然转换失败。

XAML

<UserControl.Resources>
    <appconv:CustomerNumberToStringConverter x:Key="customernumbertostringconverter" />
</UserControl.Resources>
<!-- ... -->
<ComboBox Grid.Row="4" Grid.Column="0" ItemsSource="{Binding CustomerSearchNumbers, Converter={StaticResource customernumbertostringconverter}}" SelectedItem="{Binding Path=SelectedCustomerSearchNumber, Mode=TwoWay}" /> 

视图模型

public enum CustomerIdentifier
{
    ClientPointNo = 0,
    ClientNo = 1,
    MeterNo = 2,
    CustPointNo = 3
}


public ObservableCollection<CustomerIdentifier> CustomerSearchNumbers { get; private set; }

CustomerSearchNumbers = new ObservableCollection<CustomerIdentifier>((IEnumerable<CustomerIdentifier>)Enum.GetValues(typeof(CustomerIdentifier)));

CONVERTER

public class CustomerNumberToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        var enumValue = (CustomerIdentifier)value;
        switch (enumValue)
        {
            case CustomerIdentifier.ClientPointNo:
                return XxxUtility.GetString("strclientpointno");
            case CustomerIdentifier.ClientNo:
                return XxxUtility.GetString("strclientno");
            case CustomerIdentifier.MeterNo:
                return XxxUtility.GetString("strmeterno");
            default:
                return XxxUtility.GetString("strcustomerpointno");
        }
    }
}

1 个答案:

答案 0 :(得分:4)

因为这是转换器的工作原理 - 它允许您转换绑定中的源项,在本例中为CustomerSearchNumbers。如果您要转换ComboBox中的每个项目,则需要指定使用转换器的自定义ItemTemplate

<ComboBox ItemsSource="{Binding CustomerSearchNumbers}">
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Converter={StaticResource customernumbertostringconverter}"/>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>