Dannys19 Dannys19 - 3 months ago 11
C# Question

Detecting if a string is a url

I'm printing out a url from a data set within my xaml file. The issue is, is that I'm required to only create a hyperlink if the string is a valid URL.

I know how to do this in most languages, but not in WPF. I'm looking for something that works as;

if(isurl)
display hyperline gridrow
else
display string gridrow


My xaml at present is;

<u:GridViewColumnEx x:Uid="column_4" Width="225" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink>
<TextBlock Text="{Binding Data.path}"/>
</Hyperlink>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</u:GridViewColumnEx>


But this displays everything in the column as a hyperlink (obviously). I've read about triggers but am not sure if this is what I'm after. I've read quite a bit about triggers, but am unsure on how to alter the xaml based on the return value.

Answer

One way to solve this problem is to make a boolean property which indicates the validity of the URL. Then in XAML you can have two controls in the datatemplateof your GridViewColumn.CellTemplate one a hyperlink and other a TextBlock. you have to change the visibility of the controls based on the boolean property by using triggers:

                <DataTemplate>
                <Grid>
                    <TextBlock Visibility="Collapsed" Name="Hyperlink">
            <Hyperlink NavigateUri="{Binding Data.path}">
            </Hyperlink>
                    </TextBlock>
            <TextBlock Visibility="Collapsed" Name="simpleText"
                       Text="{Binding Data.path}"></TextBlock>
                </Grid>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Data.IsValidURL}" //your boolean property
                                 Value="True">
            <Setter TargetName="Hyperlink"
                                Property="Vibility"
                                Value="Visible" />
                    </DataTrigger>
            <DataTrigger Binding="{Binding Data.IsValidURL}" //your boolean property
                                 Value="False">
            <Setter TargetName="simpleText"
                    Property="Vibility"
                    Value="Visible" />
            </DataTrigger>
            <DataTemplate.Triggers>
            </DataTemplate>