Mc Kevin Mc Kevin -4 years ago 218
C# Question

How can I cast string to Uri in xaml?

<UserControl xmlns=""
Width="1024" Height="1280">
<Grid Background="Black">
<Image MaxWidth="500" MaxHeight="500" Source="{DynamicResource H_ThankYou_Image}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<BitmapImage x:Key="H_ThankYou_Image" UriSource="{DynamicResource H_ThankYou_ImagePath}"/>
<sys:String x:Key="H_ThankYou_ImagePath">"../../../../Graphics/Icon_Email.png"</sys:String>

It says an object of type System.String cannot be applied to a property that expects the type System.Uri.

when I try something like this:

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

it says the name "uri" does not exist in the System namespace??


I tried using the solution @Clemens suggested:
It works for the first run(Icon_Email.png), however when I'm trying to dynamically change the value like this:
userControl.Resources["H_ThankYou_ImagePath"] = "../../../../Graphics/Icon_Email2.png"

the follow error occurs:

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

Answer Source

This ugly hack works for me:

<Image DataContext="{DynamicResource H_ThankYou_ImagePath}" Source="{Binding}"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download