【问题标题】:WPF - using CroppedBitmap in DataTemplateWPF - 在 DataTemplate 中使用 CroppedBitmap
【发布时间】:2010-12-15 05:34:38
【问题描述】:

以下 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"/>

什么给了?

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

【问题讨论】:

  • Bea Stollnitz 博客的链接已失效,我找不到存档。

标签: wpf data-binding datatemplate crop bitmapimage


【解决方案1】:

我想我会通过提供提到的转换器来完成 the other answer

现在我使用这个转换器,它似乎可以工作,不再有 Source' property is not set 错误。

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();
    }
}

【讨论】:

  • 提到的 Bea Stollnitz 的博客现在已经消失了——我不确定在哪里/如何使用你的转换器。我尝试了&lt;CroppedBitmap Source="{Binding PortraitPath, Converter={StaticResource croppedBitmapConverter}}" SourceRect="{Binding PortraitBounds}"/&gt;,但我仍然收到Source 属性未设置错误。碰巧记得你是怎么做到的?
【解决方案2】:

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

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

【讨论】:

  • 我知道这是一个非常古老的话题,但我遇到了同样的问题。我需要制作什么转换器?感谢您的帮助!
  • 你能扩展一下需要转换器的地方吗?对于哪个属性?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 2010-10-04
  • 2013-05-29
  • 1970-01-01
相关资源
最近更新 更多