WPF - 在 DataTemplate 中使用 CroppedBitmap
以下 xaml 在 Window
中工作正常:
<Border Width="45" Height="55" CornerRadius="10" >
<Border.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<CroppedBitmap Source="profile.jpg" SourceRect="0 0 45 55"/>
</ImageBrush.ImageSource>
</ImageBrush>
</Border.Background>
</Border>
但是当我在 DataTemplate
中使用等效代码时,我在运行时收到以下错误:
对象初始化失败 (ISupportInitialize.EndInit)。 '来源' 属性未设置。对象错误 'System.Windows.Media.Imaging.CroppedBitmap' 在标记文件中。
内部异常: {“未设置'Source'属性。”}
唯一的区别是我对 CroppedBitmap
的 Source 属性进行了数据绑定:
<CroppedBitmap Source="{Binding Photo}" SourceRect="0 0 45 55"/>
什么给出了?
更新:根据Bea Stollnitz 的旧帖子这是 CroppedBitmap
的源属性的限制,因为它实现了 ISupportInitialize
。 (此信息位于页面下方 - 搜索“11:29”,您就会看到)。
.Net 3.5 SP1 仍然存在这个问题吗?
The following xaml works ok inside a Window
:
<Border Width="45" Height="55" CornerRadius="10" >
<Border.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<CroppedBitmap Source="profile.jpg" SourceRect="0 0 45 55"/>
</ImageBrush.ImageSource>
</ImageBrush>
</Border.Background>
</Border>
But when I use the equivalent code in a DataTemplate
I get the following error in run-time:
Failed object initialization
(ISupportInitialize.EndInit). 'Source'
property is not set. Error at object
'System.Windows.Media.Imaging.CroppedBitmap'
in markup file.
Inner Exception:
{"'Source' property is not set."}
The only difference is that I have the CroppedBitmap
's Source property data-bound:
<CroppedBitmap Source="{Binding Photo}" SourceRect="0 0 45 55"/>
What gives?
UPDATE: According to an old post by Bea Stollnitz this is a limitation of the source property of the CroppedBitmap
, because it implements ISupportInitialize
. (This information is down the page - do a search on "11:29" and you'll see).
Is this still an issue with .Net 3.5 SP1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 XAML 解析器创建 CroppedBitmap 时,它执行等效操作:
EndInit()
要求Source
为非 null。当您说
c.Source=...
时,该值始终在EndInit()之前设置,但如果您使用c.SetBinding(...)
,它尝试立即进行绑定,但检测到DataContext
尚未设置。因此它将绑定推迟到以后。因此,当调用EndInit()
时,Source
仍然为 null。这解释了为什么在这种情况下需要转换器。
When the XAML parser creates CroppedBitmap, it does the equivalent of:
EndInit()
requiresSource
to be non-null.When you say
c.Source=...
, the value is always set before the EndInit(), but if you usec.SetBinding(...)
, it tries to do the binding immediately but detects thatDataContext
has not yet been set. Therefore it defers the binding until later. Thus whenEndInit()
is called,Source
is still null.This explains why you need a converter in this scenario.
我想我可以通过提供提到的转换器来完成另一个答案。
现在我使用这个转换器,似乎可以工作,不再出现 Source' property is not set 错误。
I thought I would complete the other answer by providing the alluded-to Converter.
Now I use this converter and that seems to work, no more Source' property is not set error.