2

以下 xaml 在 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>

但是当我在 a 中使用等效代码时,DataTemplate我在运行时收到以下错误:

对象初始化失败 (ISupportInitialize.EndInit)。 未设置 “源”属性。标记文件中的对象“System.Windows.Media.Imaging.CroppedBitmap” 出错。内部异常:{“'Source' 属性未设置。”}

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

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

是什么赋予了?

更新:根据Bea Stollnitz 的一篇旧帖子,这是对 source 属性的限制CroppedBitmap,因为它实现了ISupportInitialize. (此信息在页面下方 - 搜索“11:29”,您会看到)。
这仍然是 .Net 3.5 SP1 的问题吗?

4

2 回答 2

3

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

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

EndInit()要求Source为非空。

当您说c.Source=...时,该值始终在 EndInit() 之前设置,但如果您使用c.SetBinding(...),它会立即尝试执行绑定但检测到DataContext尚未设置。因此,它将绑定推迟到以后。因此,当EndInit()被调用时,Source仍然为空。

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

于 2009-11-13T00:16:17.027 回答
0

我想我会通过提供提到的转换器来完成另一个答案。

现在我使用这个转换器,这似乎工作,没有更多的 Source' 属性未设置错误。

public class CroppedBitmapConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        FormatConvertedBitmap fcb = new FormatConvertedBitmap();
        fcb.BeginInit();
        fcb.Source = new BitmapImage(new Uri((string)value));
        fcb.EndInit();
        return fcb;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
于 2013-07-25T07:42:21.847 回答