.net – 绑定到DataContext属性的Attached属性

我有一个像这样的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的View:

<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上的属性的附加属性?

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

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

Binding to AttchedProperty

点赞