views:

957

answers:

1

I've got a UserControl that contains a menu. I need to bind the Menu.Icon to a property of the UserControl but it's not working.

The code starts like this -

        <Border Grid.Row="0">            
        <DockPanel>
            <Image x:Name="testImage" Height="16" Width="16" Source="{Binding ElementName=UC,Path=AddImage}"/>
            <Menu DockPanel.Dock="Left" Height="20"
              VerticalAlignment="Center">
                <MenuItem Header="{Binding ElementName=UC,Path=AddText}">
                    <MenuItem.Icon>
                        <!--<Image x:Name="workswhenin" Height="16" Width="16" Source="pack://application:,,/Kowdox;component/Images/UserIcons/user_add.png"/>-->

                        <Image x:Name="realImage" Height="16" Width="16"
                        Source="{Binding ElementName=UC,Path=AddImage}"/>
                    </MenuItem.Icon>
                </MenuItem>

The first Image you see declared (testImage) works perfectly so I'm happy that the binding is correct. The second Image (commented out and named 'workswhenin') contains the pack URI that I'm passing to the UserControls bound property and that works too but the third one (realImage) doesn't appear at all!

I can't see ANY reason why it shouldn't work; i know the binding is good and i know that the image's placement in the markup is good so what's going on?

Any help will be greatly appreciated. Thanks in advance.

+1  A: 

Can't tell for sure because I can't see your code behind, but I'm pretty sure I know what the problem is.

Image.Source expects an object of type ImageSource. When you specify the URL in XAML a default WPF converter is used to convert the URL into an ImageSource object. Because you are using a binding, the default converter is not used. So you are probably trying to set the image source to a URL value instead of an ImageSource object.

In your code behind property, you will have to create an ImageSource object, which is really a pain. You could create a BitmapImage and pass in the URL.

The easiest solution is to use Microsoft's default converter in the code behind property that you are binding to, or use it in the binding explicitly. The converter is called ImageSourceConverter.

I can post some example code if that would be helpful.

Josh G