2016-11-20 56 views
0

目前,我爲樹的每個父標籤添加一個特定的圖標。我多次評估父節點的相同值。這是非常耗時的。有沒有簡化的方法可以在XAML中實現?可能是一個枚舉被聲明爲窗口資源?WPF替代DataTriggers序列

<!-- custom icons for the root nodes --> 
    <DataTrigger Binding="{Binding Path=Header.NodeTitle, RelativeSource={RelativeSource AncestorType=TreeViewItem, AncestorLevel=2}}" 
      Value="Sequences"> 
     <Setter Property="Source" 
     TargetName="Folder" 
     Value="/Images/sequence.png" /> 
    </DataTrigger> 
    <DataTrigger Binding="{Binding Path=Header.NodeTitle, RelativeSource={RelativeSource AncestorType=TreeViewItem, AncestorLevel=2}}" 
      Value="Triggers"> 
     <Setter Property="Source" 
     TargetName="Folder" 
     Value="/Images/trigger.png" /> 
    </DataTrigger> 
    <DataTrigger Binding="{Binding Path=Header.NodeTitle, RelativeSource={RelativeSource AncestorType=TreeViewItem, AncestorLevel=2}}" 
      Value="Views"> 
     <Setter Property="Source" 
     TargetName="Folder" 
     Value="/Images/view.png" /> 
    </DataTrigger> 

回答

0

您可以使用綁定轉換器是這樣的:

public class NodeTitleToImageConverter : IValueConverter 
{ 
    private static Dictionary<string, string> uris = new Dictionary<string, string>() 
    { 
     { "Sequences", "pack://application:,,,/Images/sequence.png" }, 
     { "Triggers", "pack://application:,,,/Images/trigger.png" }, 
     { "Views", "pack://application:,,,/Images/view.png" }, 
    }; 

    public object Convert(
     object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     string uri; 
     return uris.TryGetValue(value as string, out uri) 
      ? new BitmapImage(new Uri(uri)) 
      : null; 
    } 

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

而是多個DataTriggers的,現在就可以編寫一個綁定這樣的:

Source="{Binding Header.NodeTitle, 
    RelativeSource={RelativeSource AncestorType=TreeViewItem, AncestorLevel=2} 
    Converter={StaticResource NodeTitleToImageConverter}}" 

或樣式二傳手:

<Setter Property="Source" TargetName="Folder" 
    Value="{Binding Header.NodeTitle, 
     RelativeSource={RelativeSource AncestorType=TreeViewItem, AncestorLevel=2} 
     Converter={StaticResource NodeTitleToImageConverter}}" />