下面的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的源属性数据绑定:

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

什么给?

<强>更新根据一个旧发布者衣Stollnitz 这是CroppedBitmap的源属性的限制,因为它实现ISupportInitialize。 (此信息是下跌的一页 - 做一个搜索的“11:29”,你会看到)结果。 这是否仍与.net 3.5 SP1的问题吗?

有帮助吗?

解决方案

当的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仍然是空。

这就是为什么你需要在这种情况下的转换器。

其他提示

我想我会完成对方的回答通过提供提到到转换器。

现在我用这个转换器,似乎工作,没有更多的来源”属性设置错误。

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();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top