首页 > 解决方案 > 运行时的 WPF 绑定不起作用

问题描述

将 .NET 4.7.1 WPF 与 MahApps 1.6.1.4 一起使用。我正在绑定 HamburgerMenuIconItem.Icon 像这样:

<controls:HamburgerMenuIconItem.Icon>
<Ellipse">
    <Ellipse.Fill>
        <ImageBrush ImageSource="{Binding Image}" />
    </Ellipse.Fill>
</Ellipse>
</controls:HamburgerMenuIconItem.Icon>

在设计模式下,我可以右键单击“图像”并转到我的 ViewModel 中的属性,即 UserControl.DataContext。正如预期的那样。

但是在运行时,这会失败并出现以下错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'Image' property not found on 'object' ''HamburgerMenuIconItem' (HashCode=44346036)'. BindingExpression:Path=Image; DataItem='HamburgerMenuIconItem' (HashCode=44346036); target element is 'ImageBrush' (HashCode=21345065); target property is 'ImageSource' (type 'ImageSource')

所以在运行时它试图绑定到“HamburgerMenuIconItem”中的一个属性或什么?我可以像这样强制绑定到后面的 View 代码:

{Binding Path=Image, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}

它在运行时也有效,但我想要我的 ViewModel 中的属性。

我有什么误解?

标签: wpfdata-bindingmahapps.metro

解决方案


似乎问题是缺少 DataContext 的继承(但仅在运行时)。这里解释的解决方案解决了我的问题。


推荐阅读