绑定到数据上下文属性的附加属性

4

我有一个类似这样的 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个回答

1

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

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

绑定到附加属性


抱歉,但这不是有效的语法!ShowingPage.(AttachedProperties.Icon)是不正确的。看起来它是将 AttachedProperty 绑定和通常的绑定结合在一起。 - Hamed Zakery Miab
@HamedZakeryMiab 你测试过了吗?在同样的情况下,这个组合完美地运作。 - Reza ArabQaeni
@HamedZakeryMiab 请在调试模式下报告绑定错误的输出窗口(比如BindingExpression路径错误:'...'属性在'对象'上未找到),我确信这个语法除了在传递Datacontext时可能会有问题之外,没有其他问题。 - Reza ArabQaeni
完全无法编译!远离调试错误。你真的测试过吗? - Hamed Zakery Miab
@HamedZakeryMiab,您仍然无法将Image的Source属性绑定到ImageBrush。 - Clemens
显示剩余2条评论

1

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接