2011-10-02 103 views
0

我創建了一個包含Image控件的自定義控件。如何將圖像的源文件綁定到附加屬性?

我想將圖像控件的源代碼綁定到ImageSource依賴項屬性。

依賴屬性是這樣創建的:

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))); 
    } 
} 

而且我想綁定的自定義控件這樣形象的來源:

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

我將用戶控件放置在我的視圖中,如下所示:

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

我在啓動應用程序獲得在輸出窗口出現以下錯誤:

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

爲什麼不能在用戶控件綁定到依賴屬性?它是否在代碼隱藏中查找依賴項屬性並找不到它?

+0

爲什麼使用附加屬性而不是常規依賴屬性? –

+0

我想在其他自定義控件中使用此屬性,可能需要將其圖像控件的源代碼綁定到依賴項屬性。我應該在每個自定義控件中使用一個常規的依賴屬性,它可能需要這樣的綁定...? –

+0

我嘗試了一個依賴屬性,一切正常。我如何綁定到附加屬性?我希望能夠重新使用其他自定義控件的依賴屬性。 –

回答

0

發現問題。我沒有指定綁定的相對來源。

這裏是正確的用戶控件聲明:

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

的問題是依賴屬性無法返回值,因爲依賴對象是無效的。

相關問題