Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reference converter within a resource dictionary

I've created a multibinding converter (ListItemDescriptionConverter) that will combine several values into a single string as output for ListBox items. However I don't know how to get the resource dictionary to point to the converter class in a separate .cs file. It cannot be found when I use the following markup:

            <TextBlock Style="{StaticResource BasicTextStyle}">
                <TextBlock.Text>
                    <MultiBinding Converter="StaticResource {ListItemDescriptionConverter}">
                        <Binding Path="Genres"></Binding>
                        <Binding Path="Year"></Binding>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>

Is there something else I must do within the resource dictionary to access the converter class? I cannot add the reference within Window.Resources as it needs to be within a resource dictionary so I can reuse the style throughout my app.

like image 682
ChrisUK Avatar asked Dec 23 '22 12:12

ChrisUK


1 Answers

Define the converter as a resource, for example in your App.xaml:

<Application x:Class="WpfApplication1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication8" 
             StartupUri="MainWindow.xaml">
   <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Skins\DefaultSkinDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <local:ListItemDescriptionConverter x:Key="ListItemDescriptionConverter" />
    </ResourceDictionary>
    </Application.Resources>
</Application>

You can then reference it using the StaticResource markup extension and the x:Key:

<MultiBinding Converter="{StaticResource ListItemDescriptionConverter}">

The other option is to set the Converter property to an instance of your converter class using element syntax:

<MultiBinding>
    <MultiBinding.Converter>
        <local:ListItemDescriptionConverter />
    </MultiBinding.Converter>
</MultiBinding>
like image 67
mm8 Avatar answered Mar 28 '23 22:03

mm8