LoginSignup
3
2

More than 5 years have passed since last update.

Xamlで、ObservableCollectionを使う

Posted at

どんな時に困るのか

Xamlを記述している時に、データが無いと困ることが、良くあります。
そんな時は、下記のように、d:DesignProperties.DataContextタグを使用します。

Test.xaml
<d:DesignProperties.DataContext>
  <x:Array Type="{x:Type entity:SampleInfomation}">
    </entity:SampleInfomation>
    </entity:SampleInfomation>
    </entity:SampleInfomation>
  </x:Array>
</d:DesignProperties.DataContext>

ところが、クラス内で、ObservableCollectionを利用しているとXamlに記述することができません。
ObservableCollectionというジェネリクスな型指定がだめなようです。

解決策

下記のようなクラスを用意します。
entityクラスのcsファイル内に、併記しておくと良いかも知れません。

ObservableCollection_SubItem.cs
public class ObservableCollection_SubItem : ObservableCollection<SubItem> {}
Test.xaml
<d:DesignProperties.DataContext>
  <x:Array Type="{x:Type entity:SampleInfomation}">
    </entity:SampleInfomation>
      <!-- ObservableCollectio<SubItem> Items へデータを追加 -->
      <entity:SampleInfomation.Items>
        <entity:ObservableCollection_SubItem>
          <entity:SubItem/>
          <entity:SubItem/>
          <entity:SubItem/>
        </entity:ObservableCollection_SubItem>
      </entity:SampleInfomation.Items>
    </entity:SampleInfomation>
    </entity:SampleInfomation>
  </x:Array>
</d:DesignProperties.DataContext>

Xamlだけでは、解決できませんがダミーデータを用意するときに覚えておくと便利です。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2