views:

235

answers:

1

Hi all,

I am quite new to WPF/XAML and I am currently facing a problem.

I have a solution with two projects in it, the first project is a Custom Control Library with a custom Window form control inside. The second project is a WPF application using my custom window form.

All work fine except for the form Icon. In the WPF application project I set my window icon property to "/ProjectTwoNameSpace;component/Resources/Images/Film.ico", and in the WPF custom control I try to show that image that way :

<Image Grid.Column="0" Margin="3" Width="27" Height="27">
     <Image.Source>
        <BitmapImage UriSource="{Binding Path=Icon}" />
     </Image.Source>
 </Image>

But it doesn't work, I get a error at runtime saying that the property UriSource or StreamSource must be set for my tag.

Anyone can help me ? I think it's jsut a WPF newbie problem ^^

+1  A: 

The UriSource property of a BitmapImage cannot be set as you have shown because it is of type Uri and you are trying to set it to a string. I'd say the easiest way to accomplish what you're doing is to bind your Image.Source to Icon, and then convert the string to a bitmap Image object. Assuming your control is in a window, this would look something like this

<Window.Resources>
    <converters:StringToBitmapImageConverter x:Key="stringToBitmapImageConverter" />
</Window.Resources>

...

<Image Grid.Column="0" Margin="3" Width="27" Height="27"
    Source="{Binding Path=Icon, Converter={StaticResource stringToBitmapImageConverter}}">
</Image>

And then the converter would look like:

class StringToBitmapImageConverter: IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.UriSource = new Uri(value as string);
        image.EndInit();

        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
Robin
Your solution is good, but your statement that UriSource "cannot be set through a data binding" is untrue. You **can** bind UriSource to a property of type Uri. What you can't do is bind it to a string property without a converter.
Ray Burns
I have a error when trying to paste the <Window.resources> tag saying that property Resources was not found int the window type. Where am I suppose to paste this XAML code ?
Karnalta
It doesn't work for me, I get no compilation error but the image isn't there. The icon property is correctly set because I can see the icon in the task bar but not in my custom control. Maybe the problem come from the fact that my icon property is set to the WPF application namespace and can't be found in the WPF controls library namespace ?
Karnalta