WPF - 在DataTemplate中使用CroppedBitmap [英] WPF - using CroppedBitmap in DataTemplate

查看:289
本文介绍了WPF - 在DataTemplate中使用CroppedBitmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下xaml在窗口中可以正常工作:

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>

但是当我使用等价的代码在一个 DataTemplate 我在运行时出现以下错误:

But when I use the equivalent code in a DataTemplate I get the following error in run-time:


对象初始化失败
(ISupportInitialize.EndInit)。 源
属性未设置。在标记文件中的对象
'System.Windows.Media.Imaging.CroppedBitmap'
错误。
内部例外:

{'Source'属性未设置。}

唯一的区别是我有 CroppedBitmap 的Source属性数据绑定:

The only difference is that I have the CroppedBitmap's Source property data-bound:

<CroppedBitmap Source="{Binding Photo}" SourceRect="0 0 45 55"/>

什么给了?

更新:根据 Bea Stollnitz的旧帖子,这是一个限制 CroppedBitmap 的源属性,因为它实现了 ISupportInitialize 。 (此信息在页面上 - 在11:29上进行搜索,您将看到)。

.Net 3.5 SP1还是一个问题吗?

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?

推荐答案

当XAML解析器创建CroppedBitmap时,它相当于:

When the XAML parser creates CroppedBitmap, it does the equivalent of:

var c = new CroppedBitmap();
c.BeginInit();
c.Source = ...    OR   c.SetBinding(...
c.SourceRect = ...
c.EndInit();

EndInit()需要来源为非空值。

当您说 c.Source = ... 时,该值始终设置在EndInit()之前,但是如果您使用 c.SetBinding(...),则会尝试立即执行绑定,但会检测到 DataContext 还没有设置,所以它拖延绑定到后来,所以当 EndInit()被调用时, Source 仍然为空。

When you say c.Source=..., the value is always set before the EndInit(), but if you use c.SetBinding(...), it tries to do the binding immediately but detects that DataContext has not yet been set. Therefore it defers the binding until later. Thus when EndInit() is called, Source is still null.

这就解释了为什么在这种情况下需要一个转换器。

This explains why you need a converter in this scenario.

这篇关于WPF - 在DataTemplate中使用CroppedBitmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆