2016-02-18 34 views
1
<UserControl 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" 
      xmlns:sys="clr-namespace:System;assembly=mscorlib" 
      mc:Ignorable="d" 
      Width="1024" Height="1280"> 
    <Grid Background="Black"> 
     <Image MaxWidth="500" MaxHeight="500" Source="{DynamicResource H_ThankYou_Image}" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
    </Grid> 
    <UserControl.Resources> 
    <BitmapImage x:Key="H_ThankYou_Image" UriSource="{DynamicResource H_ThankYou_ImagePath}"/> 
    <sys:String x:Key="H_ThankYou_ImagePath">"../../../../Graphics/Icon_Email.png"</sys:String> 
    </UserControl.Resources> 
</UserControl> 

它表示System.String類型的對象不能應用於期望類型System.Uri的屬性。如何將字符串轉換爲xaml中的Uri?

當我嘗試這樣的事:

<sys:Uri x:Key="H_ThankYou_ImagePath">"../../../../Graphics/Icon_Email.png"</sys:Uri> 

它說名「URI」不會在系統命名空間中?

EDIT1:

我使用該解決方案@Clemens建議嘗試: 它適用於第一次運行(Icon_Email.png),但是當我試圖動態地改變這樣的價值: userControl.Resources["H_ThankYou_ImagePath"] = "../../../../Graphics/Icon_Email2.png" 的跟隨出現錯誤:

Cannot convert '<null>' from type '<null>' to type 
'System.Windows.Media.ImageSource' for 'en-US' culture with default 
conversions; consider using Converter property of Binding. 
NotSupportedException:'System.NotSupportedException: ImageSourceConverter cannot convert from (null). 
+0

如果您直接使用'H_ThankYou_ImagePath'作爲'Image.Source'屬性的值,它應該可以工作。 WPF內置了從'string'到'ImageSource'的轉換。 – Clemens

+0

它不是它的動態資源。 Source =「../../../../ Graphics/Icon_Email.png」可以工作,但是。 –

+0

你不能使用StaticResource? – Clemens

回答

3

這醜陋的黑客對我的作品:

<Image DataContext="{DynamicResource H_ThankYou_ImagePath}" Source="{Binding}"/> 
+0

你可以看看編輯嗎? –

+1

@McKevin只是檢查它,併成功地用另一個圖像路徑字符串替換H_ThankYou_ImagePath資源。 – Clemens

0

示例:

假設Penguins.jpg文件存在於根文件夾中。

名稱空間映射

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

資源聲明

<sys1:UriBuilder x:Key="UKey"> 
     <sys1:UriBuilder.Host> 
      <x:Static Member="sys:String.Empty" /> 
     </sys1:UriBuilder.Host> 
     <sys1:UriBuilder.Scheme> 
      <x:Static Member="sys:String.Empty" /> 
     </sys1:UriBuilder.Scheme> 
     <sys1:UriBuilder.Path> 
      pack://application:,,,/Penguins.jpg 
     </sys1:UriBuilder.Path> 
    </sys1:UriBuilder> 

用法:

<Image Source="{Binding Uri, Source={StaticResource UKey}}"/> 
2

建築物的AnjumSKhan的回答是:

定義你的命名空間:

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

定義你的URI:

<sys:Uri>pack://application:,,,/YourAssemblyNameHere;component/Path/To/Image.jpg</sys:Uri> 

所以,問題是,你是引用了錯誤的裝配。只需將您的名稱空間從mscorlib更改爲System即可,您是黃金。