2014-06-14 102 views
0

不知道如何去解決這個問題。我試圖在代碼隱藏中設置一個DataGridHyperlinkColumn,以便所有鏈接都指向相同的URI,但每個鏈接都具有不同的屬性值。將DataGridHyperlinkColumn綁定設置爲URI屬性

這是我到目前爲止有:

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

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

當然dgCol.Binding是期待一個綁定對象,所以我不能只是添加一個字符串到這一點。你能幫我正確創建這個綁定嗎?

我一直沒有找到有用的東西,但也許這是因爲我不知道我應該找什麼。這裏有一些事情我一直在尋找(如果我錯過了什麼,請見諒):

回答

1

您需要使用轉換器來格式化包含的URL字符串S中的當前屬性的PersonID

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}" 
}; 

轉換器定義如下:

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

感謝這個答案。我猜'Binding.StringFormat'屬性不起作用,因爲綁定需要轉換爲URI而不是字符串。這是正確的嗎? – Ben

+1

@Ben:是的,僅當目標屬性的數據類型爲string時,才能使用StringFormat屬性。 –

相關問題