2010-08-07 58 views
2

我是WPF和MVVM(本週開始嘗試使用它)並嘗試在運行時綁定圖像資源的新手。我想顯示的項目包含一個枚舉屬性,指示項目的類型或狀態:WPF圖像源與StringFormat綁定

public class TraceEvent 
{ 
    /// <summary> 
    /// Gets or sets the type of the event. 
    /// </summary> 
    /// <value>The type of the event.</value> 
    public TraceEventType EventType { get; set; } 
} 

據我知道圖片的來源屬性有一個值轉換器採用字符串並返回的Uri對象。

<Image Source="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}" /> 

那麼,爲什麼上述工作沒有?如果我直接進入uri(沒有綁定),圖像會完美顯示。事實上,如果我做的一個TextBlock綁定和使用也顯示沒有問題,在圖像中該值的結果:

<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/> 
<Image Source="{Binding ElementName=bindingFix, Path=Text}" /> 

我敢肯定,我在做什麼可怕的錯誤的這樣一個顯而易見的事情處理圖像。

謝謝。

回答

0

我不確定這一個,但它似乎是傳遞圖像的源屬性一個字符串,它期望一個URI。所以,你必須將你的字符串轉換成一個uri對象

6

只有當目標屬性實際上是一個字符串時才使用StringFormat - Image.Source屬性是一個Uri,所以綁定引擎不會應用StringFormat。

一種替代方法是使用Value Converter。可以編寫一個在ConverterParameter中採用字符串格式的通用StringFormatConverter,或者一個更具體的ImageSourceConverter例如

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    return string.Format("/Images/{0}Icon.ico", value); 
} 

請注意,如果您的影像生活在,因爲它們使用相同的組件,那麼你不應該需要指定URI中的組件名稱和上面的語法應該工作。