使用列表<>作为gridview中的converterparameter

时间:2012-01-04 12:50:18

标签: wpf gridview binding converter

我希望能够在我的代码中使用查找表(列表)将整数转换为字符串。 整数和列表都从COM传递并绑定到我的代码中的observable。

<ListView Name="IdList" MaxWidth="310" Height="190" Margin="5" SelectionMode="Single" 
          ItemsSource="{Binding Path=TypeItem.Ids}">'

<GridViewColumn Width="Auto" 
                DisplayMemberBinding="{Binding Path=ShipType, 
                    Converter={StaticResource ShipTypeConverter}, 
                    ConverterParameter={x:Static vm:ConfigStaticItem.alternatives_shiptype}}"/>`

我尝试过使用multibinding,但只获得了DependencyProperty.UnsetValue作为列表值

<GridViewColumn Width="Auto">
  <GridViewColumnHeader Content="ShipType"/>
  <GridViewColumn.DisplayMemberBinding >
    <MultiBinding Converter="{StaticResource ShipTypeMultiConverter}">
      <Binding Path="ShipType"/>
      <Binding Path="ConfigStaticItem.alternatives_shiptype"/>
    </MultiBinding>
  </GridViewColumn.DisplayMemberBinding>
</GridViewColumn>

[ValueConversion(typeof(byte), typeof(string))]
public class ShipTypeMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            byte state = (byte)values[0];
            List<StaticId> list = (List<StaticId>)values[1];
            return state.ToString();
        }

        catch
        {
            return "";
        }
    }

还尝试使用模板,但我想我在XAML中迷路了:)。

vm是对我的ViewModel的引用 TypeItem.Ids定义为List,其中Static是一个可观察的类,其中包含ShipType值

有人有任何建议如何解决这个问题吗?enter code here

1 个答案:

答案 0 :(得分:3)

解决方案是:

  1. 将资源添加到资源字典

    <CollectionViewSource
        x:Key="ShipTypeSource"
        Source="{Binding ConfigStaticItem.alternatives_shiptype}"
        />
    
  2. 使用标准绑定与静态资源作为转换器参数

    <GridViewColumn
        Width="Auto"
        Header="Ship Type"
        DisplayMemberBinding="{Binding Path=ShipType, Converter={StaticResource ShipTypeConverter},
        ConverterParameter={StaticResource ShipTypeSource}}"
        />
    
  3. 使用单值转换器

    [ValueConversion(typeof(byte), typeof(string))]
    public class ShipTypeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                Alternatives ShipTypes = (Alternatives)((parameter as CollectionViewSource).Source);
                byte Type = (byte)value;
                foreach (var key in ShipTypes)
                {
                    if ((uint)Type == key.Key)
                    {
                        return key.Value;
                    }
                }
                return ""; // Ship type is undefined
            }
    
            catch
            {
                return "";
            }
        }
    
        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            return null;
        }
    }