1

I want to be able to display hyperlink if the Url is not null, otherwise I do not wish to display the link.

How shall i go about this? Here is my code so far. Example of my list box template:

<ListBox.ItemTemplate>                            
  <DataTemplate>
   <StackPanel Background="#CD85C9E9" 
            Name="spListItem" 
            Orientation="Horizontal" 
            HorizontalAlignment="Stretch">
     <Label>
       <TextBlock Text="{Binding Name}" />

       <!-- How to define if Url Is Null -->
       <Hyperlink Name="MyLink" Click="MyLink_Click" /> 
    </Label>                                    
  </StackPanel>
 </DataTemplate>
</ListBox.ItemTemplate>

My Class:

public class MyList
{
    public string Name{get;set;}
    public string? Url{get;set;}
}

2 Answers 2

3

Two options:

  1. Write a custom value converter to convert an object (your Url in this case) to a Visibility based on whether it is null or not, and set that on your Visibility property:

  2. Use a DataTrigger to set the visibility to false.

    <Hyperlink Name="MyLink" Click="MyLink_Click">
        <Hyperlink.Style>
            <Style TargetType="Hyperlink">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Url}" Value="{x:Null}">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Hyperlink.Style>
    </Hyperlink>
    

The second is more verbose, but can be done entirely in xaml. However, in the first case, you will end up using the custom converter more than once.

And by the way

public string? Url{get;set;}

String is a reference type so is already nullable.

Sign up to request clarification or add additional context in comments.

1 Comment

like your usage of triggers upping for this...the string, it was just to empesize that is null. your comment made me read up more about triggers
1

I would suggest you following MVVM pattern so all business logic details are encapsulated by ViewModel (or at least keep it in code behind rather than complex View triggers, etc).

So basically you can expose property

public bool IsUrlProvided { get; private set; }

Which encapsulates all logic which is aware of right URL format details and in View just bind Visibility to this flag usng BooleanToVisibilityConverter.

<Button Visibility="{Binding IsUrlProvided, 
                    Converter={StaticResource BooleanToVisibilityConverter}}" />

In this way you do not need to change a View each time as logic changes

1 Comment

Simple way.. wonder why i did not thought about it... :) thnx a bunch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.