gpt4 book ai didi

.net - 绑定(bind)到 DataContext 属性的附加属性

转载 作者:行者123 更新时间:2023-12-04 00:24:25 27 4
gpt4 key购买 nike

我有一个这样的 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 的 View 对象作为 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>>显示页面的图标? 或者是否可以绑定(bind)到 DataContext 上的属性的附加属性?

最佳答案

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

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

Binding to AttchedProperty

关于.net - 绑定(bind)到 DataContext 属性的附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30701701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com