0

私のデータベーステーブル(名前:タグ)はこんな感じです

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

1 つのリスト ビューがあり、そのデータ テンプレートには 2 つのテキスト ブロックが含まれています。1 つはノート名用で、もう 1 つはタグ用です。

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

Note_Tagテーブルは保存NoteIDに使用されTagID 、このような単一のテキストブロックで結果が必要です

Home, Study, Research

では、データバインディングを介してどのように達成できますか?

4

1 に答える 1

0

データバインディング値コンバーターを利用する必要があります。コンバーターを使用すると、行の各値を取得し、必要に応じて連結して、連結された文字列を返すことができます。

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

コード サンプル: Name パラメーターと Tags パラメーターを持つ Note というモデル クラスがあるとします。

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

「Binding Item」は、リスト内の個々の要素を指すことに注意してください。データ ソースの定義方法に応じて、必要に応じてこれを変更する必要があります。

于 2012-10-08T07:42:08.537 に答える