2013-08-20 57 views
0

我有我的UI我的資源部分定義的一些圖片:如何引用轉換器中的資源圖像?

<Window.Resources> 
    <!-- Converters --> 
    <loc:UserStatusToIconConverter x:Key="UserStatusToIconConverter" /> 

    <!-- Images --> 
    <BitmapImage x:Key="ConnectIcon" UriSource="/WPFClient;component/Images/connect.png" /> 
    <BitmapImage x:Key="ActiveIcon" UriSource="/WPFClient;component/Images/active.png" /> 
    <BitmapImage x:Key="IdleIcon" UriSource="/WPFClient;component/Images/idle.png" /> 
    <BitmapImage x:Key="AwayIcon" UriSource="/WPFClient;component/Images/away.png" /> 
    <BitmapImage x:Key="UnknownIcon" UriSource="/WPFClient;component/Images/unknown.png" /> 
... 

我想選擇其中一個,在我的轉換器結合,我認爲這將是更有效的不是創建一個新形象每次(500次)從轉換器。

public class UserStatusToIconConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     string userStatus = value.ToString(); 
     string iconName = ...; 

     switch (userStatus) 
     { 
      case "Active": 
       // select ActiveIcon; 
       break; 
      case "Idle": 
       // select IdleIcon; 
       break; 
      case "Away": 
       ... 
       break; 
     } 

     return iconName; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

這裏是我使用它:

  <ListBox ItemsSource="{Binding Users}"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <DockPanel> 
          <Image Source="{Binding Status, Converter={StaticResource UserStatusToIconConverter}}" Height="16" Width="16" /> 
          <TextBlock Text="{Binding Nick}" /> 
         </DockPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 
+0

爲什麼有新的問題? – Clemens

回答

2

我認爲你最好使用DataTemplate.Triggers在這而不是轉換器:

    <DataTemplate> 
        <DockPanel> 
         <Image x:Name="Img" Height="16" Width="16" /> 
         <TextBlock Text="{Binding Nick}" /> 
        </DockPanel> 

        <DataTemplate.Triggers> 
         <DataTrigger Binding="{Binding Status}" Value="Active"> 
          <Setter TargetName="Img" Property="Source" Value="{StaticResource ActiveIcon}"/> 
         </DataTrigger> 

         <DataTrigger Binding="{Binding Status}" Value="Idle"> 
          <Setter TargetName="Img" Property="Source" Value="{StaticResource IdleIcon}"/> 
         </DataTrigger> 

         <!-- And So on... --> 

        </DataTemplate.Triggers> 
       </DataTemplate> 
0

你可能只是做你的轉換方法如下:

return Application.Current.MainWindow.FindResource(iconName); 
+1

雖然我個人更喜歡使用DataTriggers,正如其他答案中所建議的那樣。 – Clemens