3

UserControlオブジェクトのコレクションを含むことができる依存関係プロパティを に追加したいと考えていUIElementます。コントロールを派生させてそのプロパティをPanel使用する必要があると提案するかもしれませんChildrenが、私の場合、それは適切な解決策ではありません。

私は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'.

コレクション構文を使用してプロパティを設定するセクションでは、次のように明示的に述べられています。

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

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

4

2 に答える 2

5

プロパティのタイプを から に変更したところUIElementCollectionCollection<UIElement>問題が解決したようです。

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);
    }
  }

}

WPFUIElementCollectionには論理ツリーとビジュアル ツリーをナビゲートする機能がいくつかありますが、Silverlight にはそれがないようです。Silverlight で別のコレクション タイプを使用しても問題はないようです。

于 2009-08-19T16:13:06.937 に答える
1

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

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

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

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

また、[ContentProperty] 属性を追加することをお勧めします。これにより、デザイン時のエクスペリエンスが少しすっきりします。

于 2009-08-19T15:51:03.613 に答える