uwpdatatemplatecode-behindvalueconverter

How to set ValueConverter for DataTemplate child in code behind


I want to access a specific control inside my DataTemplate and set it's ValueConverter from CodeBehind.

The ValueConverter should be passed in from the using page/control.

My MainPage is using UserControls from a different project, because they should be used in most of my applications.

The UserControl looks like this:

<Grid>
    <ListView Name="SampleListView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Name="SampleGrid">
                    <TextBlock Name="SampleTextBox" Text="{Binding BindingProperty}" />
                    <TextBlock Name="TextBoxIWantToAccess" Foreground="{Binding SampleDateTime, Converter={StaticResource DateTimeToColorConverter}}"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

So my suggestion was first to access it from code behind but it did not work...

I've tried this: Binding(Converter) in Code Behind

in combination with this: WPF How to access control from DataTemplate

but it did not work

So now my suggestion is that I could also do it like this in code

public MyUserControl1(IValueConverter converter)
    {
        this.InitializeComponent();
        this.Resources.Add("DateTimeToColorConverter", converter);
    }

But it did not work...

Maybe it is ... Converter={StaticResource DateTimeToColorConverter}}" and it should not be specified as a StaticResource because it is from CodeBehind

But I tried a lot of combinations and it did not work...

Any suggestions?


Solution

  • The following works for me:

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <ListView>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}"
                                   Foreground="{Binding Converter={StaticResource MyConverter}}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    

    In code behind:

    public MyUserControl1()
    {
        this.Resources["MyConverter"] = new FooConverter();
        this.InitializeComponent();            
    }
    

    Note that I add the resource before calling InitializeComponent().