2

次の 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>

しかし、同等のコードを a で使用するとDataTemplate、実行時に次のエラーが発生します。

オブジェクトの初期化に失敗し ました (ISupportInitialize.EndInit)。「ソース」 プロパティが設定されていません。 マークアップ ファイルのオブジェクト'System.Windows.Media.Imaging.CroppedBitmap'でエラーが発生しました。 内部例外: {"'Source' プロパティが設定されていません。"}

唯一の違いは、CroppedBitmapの Source プロパティがデータ バインドされていることです。

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

何を与える?

更新: Bea Stollnitz による古い投稿によると、CroppedBitmapこれは のソース プロパティの制限ですISupportInitialize。(この情報はページの下にあります。「11:29」で検索すると表示されます)。
これはまだ .Net 3.5 SP1 の問題ですか?

4

2 に答える 2

3

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.

于 2009-11-13T00:16:17.027 に答える
0

ほのめかされたコンバーターを提供することで、他の答えを完成させると思いました。

今、私はこのコンバーターを使用していますが、それは機能しているようです.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();
    }
}
于 2013-07-25T07:42:21.847 に答える