开发者

How to bind an Image's Source to an attached property?

开发者 https://www.devze.com 2023-04-10 07:53 出处:网络
I created a custom control which contains an Image control. I\'d like to have the Source of the Image Control bound to an ImageSource Dependency Property.

I created a custom control which contains an Image control.

I'd like to have the Source of the Image Control bound to an ImageSource Dependency Property.

The Dependency Property is created as such:

public static class ImageSourceProperty
{
    public static readonly DependencyProperty CustomImageSourceProperty;

    public static ImageSource GetCustomImageSource(DependencyObject dependencyObject)
    {
        return (ImageSource)dependencyObject.GetValue(CustomImageSourceProperty);
    }

    public static void SetCustomImageSource(DependencyObject dependencyObject, ImageSource value)
    {
        dependencyObject.SetValue(CustomImageSourceProperty, value);
    }

    static ImageSourceProperty()
    {
        CustomImageSourceProperty = DependencyProperty.RegisterAttached("CustomImageSource", typeof (ImageSource), typeof (ImageSourceProperty), new PropertyMetadata(default(ImageSource)));
    }
}

And I'm trying to bind the Source of the Image of the Custom Control as such:

<UserControl
(...)
xmlns:AttachedProperties="clr-namespace:Codex.UserControls.AttachedProperties"
x:Class="Codex.UserControls.CustomControls.ImageWithBorder"
d:DesignWidth="640" d:DesignHeight="480">

<Grid x:Name="LayoutRoot">
    <Border BorderBrush="White" BorderThickness="3" CornerRadius="3">
        <Image Source="{Binding AttachedProperties:ImageSourceProperty.CustomImageSource}" Width="50" Height开发者_开发知识库="50"/>
    </Border>
</Grid>

I placed the user control in my view like this:

<CustomControls:ImageWithBorder (...) AttachedProperties:ImageSourceProperty.CustomImageSource="(...)"/>

I obtain the following error in the Output window upon launching the application:

System.Windows.Data Error: 40 : BindingExpression path error: 'AttachedProperties:ImageSourceProperty' property not found on 'object' ''ToolbarViewModel' (HashCode=20169503)'. 

Why isn't the user control able to bind to the dependency property ? Is it looking for the dependency property in its code-behind and can't find it ?


Found the problem. I was not specifying the relative source of the binding.

Here's the correct UserControl declaration:

<Image Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type CustomControls:ImageWithBorder}},Path=(AttachedProperties:ImageSourceProperty.CustomImageSource), Mode=TwoWay}" Width="50" Height="50"/>

The problem was that the Dependency Property was not able to return the value since the dependency object wasn't valid.

0

精彩评论

暂无评论...
验证码 换一张
取 消