2009-11-10 91 views
1

使用CroppedBitmap下面的XAML内Window工程确定:WPF中的DataTemplate

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

是什么赋予了?

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

回答

3

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

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

+0

我知道这是一个很老的话题,但我遇到同样的问题。我需要做什么转换器? Thx任何帮助! – PitAttack76 2013-07-25 07:30:38

0

我知道它很老,但我认为我会用Converter完成答案。 现在我使用这个转换器,似乎工作,没有更多的来源'属性不设置错误。

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

提到的Bea Stollnitz的博客现在已经消失 - 我不确定在哪里/如何使用您的转换器。我试过''但我仍然得到'Source'属性没有设置错误。发生以记住你是如何做到的? – 2016-07-13 23:07:13