Use converter on bound items in combobox

青春壹個敷衍的年華 提交于 2019-12-03 05:35:36

问题


i have a combobox which is bound to a datatable column like this:

ComboBox.DataContext = DataDataTable;                
ComboBox.DisplayMemberPath = DataDataTable.Columns["IDNr"].ToString();

The IDNr in the Column always starts with 4 letters followed with the ID Number (ex. BLXF1234) . I need to display the items in Combobox without the Letters (i need 1234 to be displayed in the combobox).

So i wrote a converter :

class IDPrefixValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            string s = value.ToString();
            if (s.Contains("BL"))
            {
                return s.Substring(4);
            }
            else
            {
                return s;
            }
        }
        return "";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }       

No, how can i tell the combobox to use the converter to display the items ? i tried this in the Xaml:

ItemsSource="{Binding}" 
DisplayMemberPath="{Binding Converter={StaticResource IDPrefixValueConverter}}"

But still not working ...any ideas ? Thanks


回答1:


You can modify the ItemTemplate of the ComboBox and use your converter:

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

Each item is bound to the items in the ItemsSource. By using the converter in the binding you are able to perform the conversion you want.



来源:https://stackoverflow.com/questions/9448862/use-converter-on-bound-items-in-combobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!