【问题标题】:WPF:不会导致问题的绑定失败(绑定按预期工作)
【发布时间】:2022-01-22 18:25:41
【问题描述】:

我的绑定失败似乎不是失败,因为绑定的所有内容都按预期工作。我猜绑定失败但在成功后立即失败(?但绑定失败警告不应该被删除吗?)。

绑定失败发生在我的一个自定义控件 (ColoredImage) 的模板(样式中)中。但是,当该自定义控件在另一个模板中用于自定义控件 (ComPortButton) 时,它只会在该模板中出现绑定失败。当我在其他地方使用 ColoredImage 控件时,我没有遇到绑定失败。

错误读取:System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。绑定表达式:路径=图像;数据项=空;目标元素是“ImageBrush”(HashCode=42371273);目标属性是“ImageSource”(类型“ImageSource”)

当我从以下位置修改模板时:

<Rectangle x:Name="Icon" Fill="{Binding Path=Color, RelativeSource={RelativeSource TemplatedParent}}" Height="{Binding Path=Height, RelativeSource={RelativeSource TemplatedParent}}" Width="{Binding Path=Width, RelativeSource={RelativeSource TemplatedParent}}" VerticalAlignment="Top">
  <Rectangle.OpacityMask>
     <ImageBrush ImageSource="{Binding Path=Image, RelativeSource={RelativeSource TemplatedParent}}"/>
  </Rectangle.OpacityMask>

到:

<Image Source="{Binding Path=Image, RelativeSource={RelativeSource TemplatedParent}}" x:Name="Icon" Height="{Binding Path=Height, RelativeSource={RelativeSource TemplatedParent}}" Width="{Binding Path=Width, RelativeSource={RelativeSource TemplatedParent}}" VerticalAlignment="Top"/>

然后我没有绑定失败,这很奇怪,因为使用了相同的绑定。提醒一下,使用此控件 (coloredimage) 在任何其他地方都不会出现绑定失败。只有当我从另一个模板中使用它时。

我该如何解决这个问题?代码按预期工作,我只是厌倦了“绑定失败”图标一直发红光。

ColoredImage 和 ComPortButton 的样式+模板都在 Generic.xaml 中。这有什么关系吗?我尝试改变在 Generic.xaml 中定义这些样式的顺序,但没有效果。

【问题讨论】:

  • 尝试设置一个随机的FallbackValue,比如ImageSource="{Binding Path=Image, FallbackValue=0, RelativeSource={RelativeSource TemplatedParent}}"/&gt;
  • 啊,ofc,不知道为什么我没想到。这解决了它谢谢。

标签: xml wpf xaml data-binding binding


【解决方案1】:

我认为,您的问题与 Image 和 ImageBrush 类之间的区别有关。第一个继承自 FrameworkElement 类,但不是第二个。

RelativeSource TemplatedParent 的行为取决于模板容器,请参阅:TemplatedParent remark

FrameworkElement 类包含 Binding 系统和 visualTree 使用的 DataContext 和 TemplatedParent 属性。

WPF 元素在层次上与两棵树 LogicalTree 和 VisualTree 相关(看看:Logical Tree and Visual Tree in WPF)。

如果您的元素不是 VisualTree 的一部分,您将收到此错误。

有关模式详情,请查看此回复WPF Error: Cannot find governing FrameworkElement for target element

【讨论】:

    猜你喜欢
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2018-03-09
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多