Buttonのようなコンテンツを指定できるタグはどうやってできるのか。
また、コレクションに関するXAMLの書き方についても扱う。
XAML側をこう書いただけでは、TestClassがないので当然こうなる。
TestClass.csに、
namespace BGST
{
public class TestClass
{
private string testProperty;
public string TestProperty
{
get
{
return testProperty;
}
set
{
testProperty = value;
}
}
}
}
TestClassを定義することで、
認識はする。
ただし、プロパティはタグ内の属性でしか指定できない。
さて、
using System.Collections.ObjectModel;
namespace BGST
{
public class TestClass
{
private string testProperty;
public string TestProperty
{
get
{
return testProperty;
}
set
{
testProperty = value;
}
}
public Collection<TestClass> TestCollection
{
get;
set;
}
}
}
自身のコレクションを持つプロパティTestCollectionを定義する。
すると、
TestCollectionサブタグの下に自身のタグを入れ子出来る。
ビルドは通る。
しかし、例外になってしまう。
using System.Collections.ObjectModel;
namespace BGST
{
public class TestClass
{
public TestClass()
{
TestCollection = new Collection<TestClass>();
}
private string testProperty;
public string TestProperty
{
get
{
return testProperty;
}
set
{
testProperty = value;
}
}
public Collection<TestClass> TestCollection
{
get;
set;
}
}
}
どうもTestCollectionにインスタンスがないのが原因のようなので、コンストラクタで生成するようにした。
動いたけど何もわからない。
さて、TestClassCollection.csを追加し、
Collection<TestClass>を別クラスのTestClassCollectionとした。
そして、
using System.Collections.ObjectModel;
using System.Windows.Markup;
namespace BGST
{
public class TestClass
{
public TestClass()
{
TestCollection = new TestClassCollection();
}
private string testProperty;
public string TestProperty
{
get
{
return testProperty;
}
set
{
testProperty = value;
}
}
public TestClassCollection TestCollection
{
get;
set;
}
}
}
として、
サブタグの下にコレクション、コレクションの下にアイテムという形にできた。
これでも動いた。
しかし、実はコレクションクラスはなくても、
動く。
これがコレクション構文。
WPF4.5入門 その9 「コレクション構文」 - かずきのBlog@hatena
さらに、
ContentProperty属性で指定したプロパティは、ButtonのContentのように中に直接書くことができる。
ContentPropertyAttribute Class (System.Windows.Markup) | Microsoft Docs
なので、
サブタグも省略できる。
これがコンテンツ構文。
WPF4.5入門 その10 「コンテンツ構文」 - かずきのBlog@hatena
これでTestClassタグを入れ子できることがわかる。
見た目は変わらないようだが・・・。
Sample/wpf/ContentPropertyAttribute/ContentPropertyAttribute/src/ContentPropertyAttribute_ at master · bg1bgst333/Sample · GitHub