如何在窗口标题中设置静态资源绑定。

7

我想在窗口标题的绑定上使用IValueConverter,以便在活动项目更改时更新。但问题是值转换器是静态资源,只有在几行后才加载:

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

接下来是转换器的定义:

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

这个程序崩溃了,可能是因为StaticResource没有被加载(我想不到其他原因),因为没有转换器时它可以正常工作。然而,我不能改变顺序。我试图将它放在 <Window.Title>标签中,但是无论我在标签中放什么都会出现编译错误。做这件事的正确方法是什么?


如果您使用<Window.Title>,会出现什么错误? - Mike Strobel
要么出现“属性标题没有值”的错误,要么出现“未找到某个类”的错误。但我承认我不太知道如何使用这个标记,这并没有帮助到我。 - Yellow
我模糊地记得过去曾经遇到过这个特定属性的问题,但是我不记得具体细节了。等我进入办公室后,我会进行实验。 - Mike Strobel
Sheridan再次拯救了一天,但如果你想要另一个选项,你可以在代码中实现,就像这个问题中所示。 - Noctis
事实证明,我确实不知道如何正确使用<Window.Title> - Yellow
2个回答

19

只需使用更详细的定义

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>

目前我无法测试,但它应该可以工作。


请注意:一定要按照上面的示例保持定义的顺序。(在使用转换器之前将它们添加到“资源”中)。 - aniski

-2

正确的方法是将转换器放在你的app.xaml中。


1
我不同意 - 这将 MainWindow 逻辑放置在应用程序级别,如 @Sheridan 所示,没有必要这样做。 - AndyC
这取决于使用情况,在这种特定情况下,可能还可以。但现在每个窗口都将有一个Converter实例。将其放置在app.xaml中将创建它一次,并且每个人都可以使用那个实例。当然,在这种情况下,这不应该是太大的问题。但影响应该是清楚的。但要明确的是,app.xaml用于广泛重用资源。因此,通常最好将它们放在那里,而不考虑应用程序级别。 - dowhilefor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接