문제는 당신이 BitmapImage
경우 초기화 할 수 있다는 것입니다 ...
public string ImagePath
{
get { return new "F:/myFolder/default.png"; }
}
당신 돈 즉시 사용할 수있는 UriSource
또는 StreamSource
이 없습니다. Binding
을 통해 소스를 제공하고 있으므로 즉시 사용할 수있는 소스가 없으며 데이터 컨텍스트가 설정되고 바인딩이 처리 될 때까지 바인딩을 사용할 수 없습니다. 이는 즉시 발생하지 않습니다.
소스를 사용할 수있을 때까지 BitmapImage
의 생성을 지연해야합니다.
public class ImageConverter : IValueConverter
{
public ImageConverter()
{
this.DecodeHeight = -1;
this.DecodeWidth = -1;
}
public int DecodeWidth { get; set; }
public int DecodeHeight { get; set; }
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
var uri = value as Uri;
if (uri != null)
{
var source = new BitmapImage();
source.BeginInit();
source.UriSource = uri;
if (this.DecodeWidth >= 0)
source.DecodePixelWidth = this.DecodeWidth;
if (this.DecodeHeight >= 0)
source.DecodePixelHeight = this.DecodeHeight;
source.EndInit();
return source;
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return Binding.DoNothing;
}
}
<Image Height="100"Width="100" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image.Source>
<PriorityBinding>
<Binding Path="Model1.ImagePath" Converter="{StaticResource ImageConverter}" />
<Binding Path="Model2.ImagePath" Converter="{StaticResource ImageConverter}" />
</PriorityBinding>
</Image.Source>
</Image>
... 그리고 자원이 드롭 : 당신은 사용자 정의 변환기를 사용하여이 작업을 수행 할 수
<l:ImageConverter x:Key="ImageConverter" DecodeWidth="100" />
반환 새로운 "F : /myFolder/default.png"; 오류를 반환합니다. 예상 유형입니다. –
DecodePixelWidth 속성을 사용하기 때문에 BitmapImage를 사용해야합니다. –
죄송합니다. 해당 속성은 '문자열'... 복사 및 붙여 넣기 오류가 있어야합니다. 나는 그것을 지금 새롭게했다. – Sheridan