WPF - 在DataTemplate中使用CroppedBitmap

问题描述 投票:2回答:2

以下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'出错。 内部异常:{“'源'属性未设置。”}

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

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

是什么赋予了?

更新:根据old post by Bea Stollnitz,这是CroppedBitmap的源属性的限制,因为它实现ISupportInitialize。 (此信息在页面下方 - 在“11:29”上搜索,你会看到)。 这仍然是.Net 3.5 SP1的问题吗?

wpf data-binding datatemplate crop bitmapimage
2个回答
3
投票

当XAML解析器创建CroppedBitmap时,它执行以下操作:

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

EndInit()要求Source为非null。

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

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


0
投票

我想我会通过提供alluded-to Converter来完成the other answer

现在我使用这个转换器似乎工作,没有更多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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.