2009-07-16 62 views
0

我嘗試使用下面的代碼名爲「txtImage」到圖像的文本框的文本約束沒有結果:綁定圖像源,以TextBox.Text

<Image Source="{Binding ElementName=txtImage, Path=Text}" /> 

什麼會正確的方法是什麼?

+0

您是否獲得綁定從Visual Studio運行時輸出中的錯誤?我懷疑你可以使用String作爲ImageSource。 – Joey 2009-07-16 15:11:02

回答

1

圖像的來源需要的BitmapImage,因此嘗試使用值轉換器將字符串轉換爲圖像:

public sealed class ImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, 
          object parameter, CultureInfo culture) 
    { 
     try 
     { 
      return new BitmapImage(new Uri((string)value)); 
     } 
     catch 
     { 
      return new BitmapImage(); 
     } 
    } 

    public object ConvertBack(object value, Type targetType, 
           object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
<Image> 
    <Image.Source> 
     <BitmapImage UriSource="{Binding ElementName=txtImage, Path=Text, Converter=...}" /> 
    </Image.Source> 
</Image> 

參考:Image UriSource and Data Binding

+0

爲了達到這個目的,轉換器必須在程序代碼中被刪除嗎? – Johnathan1 2009-07-21 00:57:22