Search code examples
c#wpfbindinguridatagridcolumn

Setting the DataGridHyperlinkColumn Binding as a URI Attribute


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):


Solution

  • 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();
        }
    }