0

Not sure how to go about this. I am trying to set-up a DataGridHyperlinkColumn in the code-behind so that all the links point to the same URI but each has a different attribute value.

Here is what I have so far:

DataGridHyperlinkColumn dgCol = new DataGridHyperlinkColumn();
dgCol.Header = title;
dgCol.ContentBinding = new Binding("PersonName");

dgCol.Binding = "PersonEditPage.xaml?PersonID=" + Binding("PersonID");

Of course dgCol.Binding is expecting a Binding object and so I can't just add a string to this. Can you please help me to create this binding correctly?

I have not been able to find anything helpful, but maybe this is because I don't know what I should be looking for. Here are some things I have been looking at (If I missed something please forgive me):

Community
  • 1
  • 1
Ben
  • 3,241
  • 4
  • 35
  • 49

1 Answers1

1

You need to use a converter in order to format a URL string that contains the PersonID of the current property:

DataGridHyperlinkColumn hypCol = new DataGridHyperlinkColumn();
hypCol.Header = "Link";
hypCol.ContentBinding = new Binding("PersonName");
hypCol.Binding = new Binding("PersonID") {
    Converter = new FormatStringConverter(),
    ConverterParameter = "PersonEditPage.xaml?PersonID={0}"
};

The converter is defined as follows:

public class FormatStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || parameter == null)
        {
            return null;
        }
        return string.Format(parameter.ToString(), value.ToString());
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
  • Thanks for this answer. I guess that the `Binding.StringFormat` property doesn't work because the binding is expected to convert to a URI and not a string. Is this right? – Ben Jun 17 '14 at 21:51
  • 1
    @Ben: Yes, the `StringFormat` property can be used only if the target property has data type `string`. –  Jun 18 '14 at 03:50