Mc Kevin Mc Kevin - 3 months ago 30
C# Question

How can I cast string to Uri in xaml?

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


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

Edit1:

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

This ugly hack works for me:

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