如何使用IMultiValueConverter从相关表中查找数据

时间:2018-11-30 15:58:28

标签: c# wpf data-binding wpfdatagrid imultivalueconverter

我在DataGrid中有一个DataGridTemplateColumn,看起来像这样:

<DataGridTemplateColumn Width="3*" Header="Item">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding AssetDescriptionID} Converter={StaticResource converter}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox
                DisplayMemberPath="Description"
                ItemsSource="{Binding Data.AssetDescriptions, Source={StaticResource proxy}}"
                SelectedValue="{Binding AssetDescriptionID}"
                SelectedValuePath="AssetDescriptionID" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

我想使用多值转换器通过资产描述ID在另一行(可能是错误的)中从另一个表中查找资产描述:

<TextBlock Text="{Binding AssetDescriptionID} Converter={StaticResource converter}" />

ViewModel具有包含资产描述的公共属性:

public IEnumerable<AssetDescription> AssetDescriptions { get; set; }

AssetDescription本质上是:

public class AssetDescription
{
    public int AssetDescriptionID { get; set; }
    public string Description { get; set; }
}

所以我写了这个转换器类:

public class AssetDescriptionConverter : FrameworkElement, IMultiValueConverter
{
    public IEnumerable<T_AssetDescription> AssetDescriptions
    {
        get { return (IEnumerable<T_AssetDescription>)GetValue(AssetDescriptionsProperty); }
        set { SetValue(AssetDescriptionsProperty, value); }
    }

    public static readonly DependencyProperty AssetDescriptionsProperty =
        DependencyProperty.Register("AssetDescriptions", typeof(IEnumerable<T_AssetDescription>), typeof(AssetDescriptionConverter));

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var items = values as IEnumerable<T_Asset>;
        if (items != null)
        var item = items.FirstOrDefault(x => x.AssetDescriptionID == (int)parameter);
        return item == null ? string.Empty : item.Description;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但是我不知道如何在XAML中声明此资源,然后将其绑定到我的TextBlock。

1 个答案:

答案 0 :(得分:-1)

在资源部分:

<AssetDescriptionConverter x:Key="AssetDescriptionConverter"/>

,然后输入xaml:

<TextBlock Text="{Binding AssetDescriptionID, Converter={StaticResource AssetDescriptionConverter}}"/>