Adriaan Davel
Adriaan Davel

Reputation: 748

Add converter to page resources from code behind

I would like to add a specific instance of a class to the resources of a page then use that class as a converter, so in my page constructor I put:

this.Resources.Add("converterASD", new ASDConverter());

then bind to it like this:

<ListBox ItemsSource="{Binding Converter={StaticResource converterASD}}"/>

but I keep getting this exception:

Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.

I'm a bit new to WPF, any advice would be appreciated.

Upvotes: 2

Views: 2426

Answers (2)

Shrinand
Shrinand

Reputation: 351

You can declare the Converter you would like to use in the resource section of the page like the following example. (I recommend you declare the converter in XAML instead of the code-behind)

Example:

<UserControl x:Class="Views.ConverterExample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300"
        d:DesignWidth="300">
    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter" />
    </UserControl.Resources>
    <Grid>
        <CheckBox x:Name="VisibilityController" IsThreeState="False" />
        <ListBox
            Visibility="{Binding ElementName=VisibilityController, Path=IsChecked,Converter={StaticResource BoolToVisibilityConverter}}"
            Height="100" Width="100" BorderBrush="Red" BorderThickness="1" />
    </Grid>
</UserControl>

Upvotes: 0

Nathan Hillyer
Nathan Hillyer

Reputation: 1979

We could use more information from the exception.

Two suggestions:

  1. Make sure that you add the resource before the call to InitializeComponent().
  2. Try switching it to a dynamic resource.

Upvotes: 3

Related Questions