绑定到DataContext属性的Attached属性

时间:2015-06-08 05:20:43

标签: .net wpf vb.net

我有一个像这样的AttachedProperty:

Public Class AttachedProperties
    Public Shared ReadOnly IconProperty As DependencyProperty = DependencyProperty.RegisterAttached("Icon", GetType(ImageBrush), GetType(AttachedProperties), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender))

    Public Shared Sub SetIcon(ByVal element As Object, ByVal value As ImageBrush)
        element.SetValue(IconProperty, value)
    End Sub

    Public Shared Function GetIcon(ByVal element As Object) As ImageBrush
        Return CType(element.GetValue(IconProperty), ImageBrush)
    End Function
End Class

像这样的ViewModel:

Public Class ViewModel
    Public Property ShowingPage as Page

    Public Sub New()
        ShowingPage = New SamplePage()
    End Sub
End Class

虽然我的SamplePage是这样的:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SamplePage">
    <local:AttachedProperties.Icon>
        <ImageBrush Source="Pack://..." /> <!-- Page's Icon -->
    </local:AttachedProperties.Icon>
</Page>

最后我有一个使用ViewModel对象作为ViewModel的视图:

<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="MainWindow">

        <StackPanel>
            <!-- Showing Icon of page-->
            <Image Source="{Binding (AttachedProperties.Icon), Source=<<ShowingPage>>}" />

            <!-- Showing content of page -->
            <Frame Content="{Binding ShowingPage}" />
        </StackPanel>
    </Window>

问题是我应该写什么而不是<<ShowingPage>>来显示页面的图标?或者是否可以绑定到DataContext上的属性的附加属性?

2 个答案:

答案 0 :(得分:1)

附属属性拥有一个基于所有者设置或获取的所有者,返回该所有者的唯一值,因此您必须绑定到相对的页面控件,然后引用自己的附属属性:

<Image Source="{Binding Path=ShowingPage.(local:AttachedProperties.Icon)}" />

Binding to AttchedProperty

答案 1 :(得分:1)

首先,您无法将Image控件的Source属性绑定到类型ImageBrush的属性。您可以使用ImageSource作为附加属性的类型,或者将(例如)Rectangle的Fill属性绑定到ImageBrush。

绑定的正确语法还必须包含名称空间前缀:

<Rectangle Width="50" Height="50"
    Fill="{Binding Path=ShowingPage.(local:AttachedProperties.Icon)}" />