C# 如何在C/XAML中绑定多行导致Windows应用商店应用程序中的单个数据绑定

C# 如何在C/XAML中绑定多行导致Windows应用商店应用程序中的单个数据绑定,c#,xaml,data-binding,microsoft-metro,windows-runtime,C#,Xaml,Data Binding,Microsoft Metro,Windows Runtime,我的数据库表名:标记如下 TagID TagName ------------------------- 1 Home 2 Work 3 Office 4 Study 5 Research 我有一个列表视图,它的数据模板包含两个文本块。一个用于注释名称,另一个用于标记 lvRecentNotes.ItemsSource = db.Query<NoteDetails>("select NoteName from

我的数据库表名:标记如下

TagID       TagName
-------------------------
1       Home
2       Work
3       Office
4       Study
5       Research
我有一个列表视图,它的数据模板包含两个文本块。一个用于注释名称,另一个用于标记

lvRecentNotes.ItemsSource = db.Query<NoteDetails>("select NoteName from NoteDetails", "");
注\标记表用于保存NoteID和TagID 现在我想在一个单独的文本块中得到这样的结果

家庭、学习、研究


那么如何通过数据绑定实现呢?

您需要使用数据绑定值转换器。使用转换器,您可以获取行中的每个值,然后根据需要连接并返回连接的字符串

参考:

代码示例: 假设您有一个名为Note的模型类,它有Name和Tags参数

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;
    }
}
然后您可以设置您的项目资源

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

请注意,绑定项是指列表中的每个单独元素。根据数据源的定义方式,您需要根据需要对此进行修改。

我应该将什么作为绑定路径?你能给我一些演示代码吗?