WPF - using CroppedBitmap in DataTemplate

后端 未结 2 911
眼角桃花
眼角桃花 2021-01-22 07:54

The following xaml works ok inside a Window:


    
        &l         


        
相关标签:
2条回答
  • 2021-01-22 08:37

    When the XAML parser creates CroppedBitmap, it does the equivalent of:

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

    EndInit() requires Source to be non-null.

    When you say c.Source=..., the value is always set before the EndInit(), but if you use c.SetBinding(...), it tries to do the binding immediately but detects that DataContext has not yet been set. Therefore it defers the binding until later. Thus when EndInit() is called, Source is still null.

    This explains why you need a converter in this scenario.

    0 讨论(0)
  • 2021-01-22 08:56

    I thought I would complete the other answer by providing the alluded-to Converter.

    Now I use this converter and that seems to work, no more Source' property is not set error.

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题