How to use an IMultiValueConverter to look up data from a related table

55 Views Asked by At

I have a DataGridTemplateColumn in a DataGrid that looks like this:

<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>

I would like to use a Multi-Value Converter to lookup an Asset Description from another table by the Asset Description ID, in this (probably wrong) line:

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

The ViewModel has a public property containing the Asset Descriptions:

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

Where AssetDescription is essentially:

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

So I've written this converter class:

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();
    }
}

But I can't figure out how to declare this resource in the XAML and then bind it to my TextBlock.

1

There are 1 best solutions below

1
mami On

In the resource part:

<AssetDescriptionConverter x:Key="AssetDescriptionConverter"/>

and then in xaml:

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