ObservableCollectionの 1 つとしてを持つコントロールに取り組んでいDependencyPropertiesます。このプロパティはDefaultPropertyコントロールの として設定されるため、次のような行を作成することで、XAML のコレクションに項目を暗黙的に追加できます。
<MyControl>
<MyItem/>
<MyItem/>
<MyItem/>
</MyControl>
私の知る限り、WPF エンジンは XAML を解析するときに論理ツリーを構築します。したがって、それぞれMyItemが の論理的な子である必要がありMyControlます。逆に、MyControlは各 の論理的な親である必要がありますMyItem。
まあ、どうやらそれ以上のものがあるようです。以下は、上記の関係を定義するために使用するコードです。カスタム コントロールにはDependencyPropertyfor が含まれてObservableCollectionおり、CLR プロパティによってサポートされています。
[ContentProperty("Items")]
public class MyControl : Control
{
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
"Items",
typeof(ObservableCollection<MyItem>),
typeof(MyControl),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, OnItemsChangedProperty));
[Category("MyControl")]
public ObservableCollection<MyItem> Items
{
get { return (ObservableCollection<MyItem>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public MyControl() : base()
{ //Set a new collection per control, but don't destroy binding.
SetCurrentValue(ItemsProperty, new ObservableCollection<MyItem>());
}
}
MyItem(を継承する)からFrameworkContentElement、次のように論理的な親にアクセスしようとします。
if (Parent is FrameworkElement)
{ //Re-Render the parent control.
((FrameworkElement)Parent).InvalidateVisual();
}
驚いたことに、親コントロールは再レンダリングされません。これは、MyItem.Parentプロパティが null であるためです。どうしてこれなの?
MyControlの論理的な親であることを WPF エンジンに指示するにはどうすればよいMyItemですか?