Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a StaticResource Binding in a window Title

I want to put a IValueConverter on a binding to the title of a window, so that changes when the active project changes. The problem is that the value converter is a static resource, which is only loaded a few lines later:

<Window x:Class="MyProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyProject"
        Height="600" Width="800" VerticalAlignment="Stretch"
        Title="{Binding ActiveProject, Converter={StaticResource windowTitleConverter}},  UpdateSourceTrigger=PropertyChanged">
     <Window.Resources>
         <local:MainWindowTitleConverter x:Key="windowTitleConverter"/>
     </Window.Resources>

     <!-- Rest of the design -->
</Window>

And then the definition of the converter:

public class MainWindowTitleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return "Programme"; else return "Programme: " + (value as string);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This crashes, presumably because the StaticResource hasn't been loaded yet (I can't think of any other reason), cause without the converter it works fine. However, I can't change the order. I tried to put it in a <Window.Title> tag, but anything that I put within that tag gives a compilation error. What is the proper way of doing this?

like image 253
Yellow Avatar asked Nov 08 '13 10:11

Yellow


1 Answers

Just use the more verbose definitions

xmlns:System="clr-namespace:System;assembly=mscorlib"

...

<Window.Resources>
    <local:MainWindowTitleConverter x:Key="windowTitleConverter"/>
    ...
</Window.Resources>
<Window.Title>
    <Binding Path="ActiveProject">
        <Binding.Converter>
            <StaticResource ResourceKey="windowTitleConverter" />
        </Binding.Converter>
    </Binding>
</Window.Title>

I can't test this at the moment, but it should work.

like image 178
Sheridan Avatar answered Sep 23 '22 21:09

Sheridan