2012-10-08 22 views
0

我的數據庫表(名稱:標籤)是這樣如何綁定在單一的數據在C#中的Windows商店應用結合muliple行結果/ XAML

TagID  TagName 
------------------------- 
1  Home 
2  Work 
3  Office 
4  Study 
5  Research 

我有一個列表視圖和數據模板包含兩個文本塊。一個是筆記名稱,另一個是標籤。

lvRecentNotes.ItemsSource = db.Query<NoteDetails>("select NoteName from NoteDetails", ""); 

Note_Tag表用於保存NoteIDTagID 現在我想要的結果在這樣

Home, Study, Research

單一的文本塊因此如何通過數據綁定實現的呢?

回答

0

您需要使用數據綁定值轉換器。使用轉換器,您可以獲取該行中的每個值,然後根據需要連接並返回連接的字符串。

參考:http://msdn.microsoft.com/en-us/library/system.windows.data.binding.converter.aspx

代碼示例:假設 你已經有了一個模型類叫做注意其中有名稱和標籤的參數。

public class Note 
{ 
    public string Name { get; set; } 
    public string Tags { get; set; } 
} 

public class NoteItemConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     if (value is Note) 
     { 
      Note note = value as Note; 

      // Return a value based on parameter (when ConverterParameter is specified) 
      if (parameter != null) 
      { 
       string param = parameter as string; 
       if (param == "name") 
       { 
        return note.Name; 
       } 
       else if (param == "tags") 
       { 
        return note.Tags; 
       } 
      } 

      // Return both name and tags (when no parameter is specified) 
      return string.Format("{0}: {1}", note.Name, note.Tags); 
     } 

     // Gracefully handle other types 
     // Optionally, throw an exception 
     return string.Empty; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     return value; 
    } 
} 

然後你可以設置你的ItemsSource

ObservableCollection<Note> notes = ... // Obtain your list of notes 
lvRecentNotes.ItemsSource = notes; 

在XAML中,添加轉換器作爲網頁資源。

<Page.Resources> 
    <local:NoteItemConverter x:Key="NoteItemConverter"/> 
</Page.Resources> 

然後綁定到您的數據模板中的項目。

<!-- Display only the name for the note --> 
<TextBlock Text="{Binding Item, Converter={StaticResource NoteItemConverter}, ConverterParameter=name}"/> 

<!-- Display only the tags for the note --> 
<TextBlock Text="{Binding Item, Converter={StaticResource NoteItemConverter}, ConverterParameter=tags}"/> 

<!-- Display both the name and the tags for the note --> 
<TextBlock Text="{Binding Item, Converter={StaticResource NoteItemConverter}}"/> 

請注意,「綁定項目」是指列表中的每個單獨的元素。您需要根據需要對其進行修改,具體取決於數據源的定義方式。

+0

我應該把什麼作爲綁定路徑?你能給我一些演示代碼嗎? – Xyroid

+0

增加了一些示例代碼。 – Akinwale

相關問題