views:

1233

answers:

2

In WPF, how can I get a reference to the Command that a Hyperlink should invoke from an object property?

I am creating a WPF application, using the MVVM pattern. A list box in the main window dislays hyperlinks. Each hyperlink will invoke one of the view model's ICommand properties when it is clicked. How do I specify which ICommand should be invoked?

Here is what I have tried so far: The hyperlinks are contained in ViewModel.Hyperlinks property, which is bound as the ItemsSource for the list box. The Hyperlinks property contains objects of type MyHyperlink:

public class MyHyperlink
{
    public string Text { get; set; }
    public string ViewModelCommand { get; set; }
    public int RecordID { get; set; }
}

The MyHyperlink.ViewModelCommand property contains the name of the view model ICommand that should be invoked when the hyperlink is clicked. I want to use that value to specify a PropertyPath for the Command property of the WPF Hyperlink control . I tried creating a PropertyPath resource for the list box with the name of the command, but WPF won't accept that. Here is my XAML:

<ListBox ItemsSource="{Binding Hyperlinks}">
    <ListBox.Resources>
        <PropertyPath x:Key="CommandPath" Path="{Binding ViewModelCommand}" />
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <Hyperlink Command="{StaticResource CommandPath}"
                        CommandParameter="{Binding Path=RecordID}">
                    <TextBlock Text="{Binding Text}" />
                </Hyperlink>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

How do I specify which ICommand should be invoked when the hyperlink is clicked? Do I create a resource (as shown above), or it it done some other way? I need to do this in XAML--I don't want to resort to code-behind. Thanks for your help!

+1  A: 

I think that your code above doesn't work because Hyperlink.Command is of type ICommand, not string. You either need to modify your MyHyperlink class so that ViewModelCommand is also an ICommand, or write an IValueConverter that will find the correct ICommand implementation given the command name in your view model.

Andy
A: 

I have implemented a solution that uses an IValueConverter. It is written up as an article on The Code Project. Hopefully it will help other people down the road.

David Veeneman
In your Code Project article on Dynamic Commands, you mentioned that there was a better way than using an IValueConverter. Can you let us in on the secret?
dthrasher
Didn't pan out. I'm using IValueConverter. So, no secret.
David Veeneman