C#

ListBoxとDataTemplate

[`evernote` not found]
LINEで送る
Pocket

なんと今回はC#あるいはWPFについてです。

自分があまりにも物事を忘れやすいことを反省して、忘れないようにするためのタスク管理アプリを作りました。
その時にListBoxで困ったのでメモ。
やりたい事は、ListBoxのItemsSourceに自分で作成したクラスのプロパティのコレクションを適用させる、ということ。

Window1.xamlの一部
ListBoxの定義:

<ListBox x:Name="dataList" ItemTemplate="{StaticResource listTemplate}"/>

DataTemplateの定義(TodoEntityというのが自分で定義したエンティティクラスです。):

<DataTemplate x:Key="listTemplate" DataType="{x:Type local:TodoEntity}">
            <Grid ToolTip="{Binding Path=DescriptionValue}">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <StackPanel Orientation="Horizontal" Grid.Column="0">
                   <TextBlock Text="件名:"/>
                   <TextBlock x:Name="subject_tb" Text="{Binding Path=SubjectValue}" />
                </StackPanel>
                <StackPanel Margin="10,0,0,0" Orientation="Horizontal" Grid.Column="1">
                    <TextBlock Text="概要:"/>
                    <TextBlock Text="{Binding Path=DescriptionValue}"/>
                </StackPanel>
               
            </Grid>
        </DataTemplate>

で、これがエンティティクラスのTodoEntity

/// <summary>
        /// 終了しているか。
        /// 1: 終了
        /// 0: 未
        /// </summary>
        public int isFinished;
        /// <summary>
        /// 件名
        /// </summary>
        public string subject;
        /// <summary>
        /// 詳細
        /// </summary>
        public string description;
        /// <summary>
        /// 登録時間
        /// </summary>
        public DateTime registerDateTime;


        #region アクセサ。なぜかこうしないとデータバインドしなかった.

        public string SubjectValue
        {
            get
            {
                return subject;
            }
            set
            {
                subject = value;
            }
        }
        public string DescriptionValue
        {
            get
            {
                return description;
            }
            set
            {
                description = value;
            }
        }
        #endregion

DataTemplateにTodoEntityのsubjectプロパティを表示させたかったのですが、なぜか表示できなくて困ってたのですが、#regionに書いているようにアクセサ(SubjectValue, DescriptionValue)を作ってそれにバインドさせてやると、無事にデータが表示されました。

これなんでだろう。。。

あ、コードの書き方が統一されてなくてすみません。。。

アプリは見栄えがもう少しまともにできたらアップしますね。

コメントを残す

メールアドレスが公開されることはありません。

CAPTCHA