绑定字符串格式不起作用

时间:2016-01-07 09:12:01

标签: c# wpf xaml binding string-formatting

我有一个应用程序,在启动时,用户需要选择课程主题和课程名称。课程主题是从软件的应用程序数据文件夹中的文件夹中收集的。

我想在Word中显示像Office一样的主题,例如,您可以选择要开始的模板。在主题文件夹中是一个png,它是我想要显示的主题的图片。如果我像这样复制并粘贴直接路径:

<Image Width="600" Height="400" HorizontalAlignment="Center"   Source="C:\Users\james\AppData\Roaming\Jenison\Perform\Themes\TemplateThemes\JenisonOnyxFullScreen\thumbnail.png"    />

工作正常。但显然每个用户都有不同的用户名,所以我不能这样做。所以我这样做:

  <Image Width="600" Height="400" HorizontalAlignment="Center" Source="{Binding ThumbnailPath, StringFormat='pack://application:,,,/Themes/TemplateThemes/{0}'}"   />

绑定ThumbnailPath返回JenisonOnyxFullScreen \ thumbnail.png,所以上面是pack:// application:,,, / Themes / TemplateThemes / JenisonOnyxFullScreen \ thumbnail.png,我也把它添加到一个文本块,路径似乎是精细。但图像并没有这样显示。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

一位工作同事建议第一次完美运作的东西。我在图像中添加了一个eventsetter,如下所示:

   <Image Width="450" Height="400"  HorizontalAlignment="Center" >
                            <Image.Style>
                                <Style TargetType="Image">
                                    <EventSetter Event="Loaded" Handler="ThemeImagePath">

                                    </EventSetter>
                                </Style>
                            </Image.Style>
                        </Image>

然后在代码隐藏中添加了一个名为ThemeImagePath

的方法
    public void ThemeImagePath(object sender, RoutedEventArgs e)
    {
        var Image = (Image)sender;
        var Theme = Image.DataContext as IPerformTheme;
        Image.Source = ImageHelper.BitmapSourceFromPath(new Uri(Model.ApplicationRoots.ThemeRoot + "/TemplateThemes/" + Theme.Name + "/thumbnail.png")); 
    }

答案 1 :(得分:0)

图像使用字符串格式进行绑定,就像这样解决了

 <Image x:Name="im" Width="600" Height="400" HorizontalAlignment="Center"   Source="{Binding ElementName=test, Path=Text}"    />

  <TextBlock x:Name="test" Background="Red" Text="{Binding ThumbnailPath, StringFormat=pack://application:\,\,\,/WpfApplication1;component/Images/\{0\}}" HorizontalAlignment="Left" Margin="20,216,0,0" VerticalAlignment="Top" Height="43"/>