WPF Listbox with File Hyperlink mvvm

2019-07-22 17:37发布

问题:

I have a ListBox bound to a string ObservableCollection.

Whenever a particular string value in the ObservableCollection contains a path to a file , then it should show as a Hyperlink and when clicked it should open the file.

How to implement this in the ItemTemplate?

回答1:

You can achieve this using DataTemplateSelector

public class HyperlinkDataTemplateSelector : DataTemplateSelector
{
       public DataTemplate RegularTemplate { get; set; }

       public DataTemplate HyperlinkTemplate { get; set; }

       public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
       {
             var str = item as string;

             // Check if str contains path and return the dataTemplate accordingly

             return // Either RegularTemplate or HyperlinkTemplate 
       }
}

In xaml

<local:HyperlinkDataTemplateSelector x:Key="itemTemplateSelector">
        <local:HyperlinkDataTemplateSelector.RegulatTemplate>
            <DataTemplate>
               <TextBlock Text="{Binding Path=YourProperty}"/>  
            </DataTemplate>
        </local:HyperlinkDataTemplateSelector.RegularTemplate>
        <local:HyperlinkDataTemplateSelector.HyperlinkTemplate>
            <DataTemplate>
                    <TextBlock>
                        <Hyperlink NavigateUri="{Binding Path=YourProperty}">
                           <TextBlock Text="{Binding Path=YourProperty}" />
                        </Hyperlink>   
                    </TextBlock>
            </DataTemplate>
        </local:HyperlinkDataTemplateSelector.HyperlinkTemplate>
</local:HyperlinkDataTemplateSelector>

In your ListBox declaration use your DataTemplateSelector

 <ListBox ItemsSource="{Binding Path=YourCollection}" ItemTemplateSelector="{StaticResource itemTemplateSelector}">

Hope this helps