2009-08-19 10 views
3

に、UIElementオブジェクトのコレクションを含むことができる依存プロパティを追加したいとします。私はPanelから私のコントロールを派生させ、それにはChildrenのプロパティを使うべきだと示唆しているかもしれませんが、私の場合は適切な解決策ではありません。SilverlightでのUIElementCollection DependencyPropertyの追加

私はこのような私のUserControl変更しました:

public partial class SilverlightControl1 : UserControl { 

    public static readonly DependencyProperty ControlsProperty 
    = DependencyProperty.Register(
     "Controls", 
     typeof(UIElementCollection), 
     typeof(SilverlightControl1), 
     null 
    ); 

    public UIElementCollection Controls { 
    get { 
     return (UIElementCollection) GetValue(ControlsProperty); 
    } 
    set { 
     SetValue(ControlsProperty, value); 
    } 
    } 

} 

と私はこのようにそれを使用しています:私は、アプリケーションを実行すると

<local:SilverlightControl1> 
    <local:SilverlightControl1.Controls> 
    <Button Content="A"/> 
    <Button Content="B"/> 
    </local:SilverlightControl1.Controls> 
</local:SilverlightControl1> 

は、残念ながら、私は次のエラーを取得する:

Object of type 'System.Windows.Controls.Button' cannot be converted to type 
'System.Windows.Controls.UIElementCollection'. 

Setting a Property by Using a Collection Syntaxセクションでは、次のように明示的に記載されています。

[...] UIElementCollectionは構成可能なクラスではないため、[UIElementCollection]をXAMLで明示的に指定することはできません。

問題を解決するにはどうすればよいですか?ソリューションは単にUIElementCollectionの代わりに別のコレクションクラスを使用するだけですか?はいの場合は、使用する推奨コレクションクラスは何ですか?

答えて

5

私はUIElementCollectionからCollection<UIElement>に私の財産の種類を変更し、それが問題を解決しているようだ:WPF UIElementCollection

public partial class SilverlightControl1 : UserControl { 

    public static readonly DependencyProperty ControlsProperty 
    = DependencyProperty.Register(
     "Controls", 
     typeof(Collection<UIElement>), 
     typeof(SilverlightControl1), 
     new PropertyMetadata(new Collection<UIElement>()) 
    ); 

    public Collection<UIElement> Controls { 
    get { 
     return (Collection<UIElement>) GetValue(ControlsProperty); 
    } 
    } 

} 

は論理的でビジュアルツリーをナビゲートするためのいくつかの機能がありますが、それは存在しないと思わSilverlightで。 Silverlightで別のコレクション型を使用しても問題は発生しません。

+0

さらに簡単に - うまくいきます。私が試してみたところでは、最初のプロパティのメタデータをコレクションのインスタンスに設定するのを忘れていました。 –

1

Silverlight Toolkitを使用している場合、System.Windows.Controls.Toolkitアセンブリには、この種の作業をXAMLで簡単に行うための "ObjectCollection"が含まれています。

これは、プロパティがObjectCollection型である必要があることを意味します。そのため、UIElementに対する厳密な型指定が失われます。また、IEnumerable型(ほとんどの場合、ItemsSourceなど)の場合は、XAMLでtoolkit:ObjectCollectionオブジェクトを明示的に定義できます。

これを使用するか、単にsource to ObjectCollection(Ms-PL)を借りてプロジェクトで使用することを検討してください。

実際にコレクションシナリオでパーサを動作させる方法があるかもしれませんが、これはやや簡単です。

また、[ContentProperty]属性を追加して、設計時の操作性が少し向上するようにすることをおすすめします。

+0

あなたのご意見ありがとうございました。「ContentProperty」についてのご意見ありがとうございます(私の場合は当てはまりません)。 –

関連する問題