代码之家  ›  专栏  ›  技术社区  ›  Gus

WPF-在DataTemplate中使用裁剪位图

  •  1
  • Gus  · 技术社区  · 16 年前

    下面的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)。'来源' 属性未设置。对象错误 在标记文件中。
    内部异常:
    {未设置“源”属性。}

    CroppedBitmap

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

    有什么好处?

    更新: old post by Bea Stollnitz 裁剪位图 ,因为它实现了 ISupportInitialize
    这仍然是.NET3.5SP1的问题吗?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Ray Burns    16 年前

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

    EndInit() 要求 Source

    当你说 c.Source=... ,该值始终设置在EndInit()之前,但如果使用 c.SetBinding(...) ,它尝试立即执行绑定,但检测到 DataContext EndInit() 叫做, 来源 仍然为空。

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

        2
  •  0
  •   StayOnTarget Charlie Flowers    7 年前

    我想我会完成的 the other answer 通过提供暗指转换器。

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