WPF列表框与文件超链接mvvm

时间:2013-09-28 12:01:57

标签: wpf hyperlink listbox

我有一个绑定到字符串ObservableCollection的ListBox。

每当ObservableCollection中的特定字符串值包含文件路径时,它应显示为超链接,单击时应打开该文件。

如何在ItemTemplate中实现它?

1 个答案:

答案 0 :(得分:1)

您可以使用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 
       }
}

在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>

ListBox声明中使用DataTemplateSelector

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

希望这有帮助