您需要使用數據綁定值轉換器。使用轉換器,您可以獲取該行中的每個值,然後根據需要連接並返回連接的字符串。
參考: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}}"/>
請注意,「綁定項目」是指列表中的每個單獨的元素。您需要根據需要對其進行修改,具體取決於數據源的定義方式。
我應該把什麼作爲綁定路徑?你能給我一些演示代碼嗎? – Xyroid
增加了一些示例代碼。 – Akinwale