【发布时间】: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}}"/>。 -
啊,ofc,不知道为什么我没想到。这解决了它谢谢。
标签: xml wpf xaml data-binding binding