ObservableCollection
の 1 つとしてを持つコントロールに取り組んでいDependencyProperties
ます。このプロパティはDefaultProperty
コントロールの として設定されるため、次のような行を作成することで、XAML のコレクションに項目を暗黙的に追加できます。
<MyControl>
<MyItem/>
<MyItem/>
<MyItem/>
</MyControl>
私の知る限り、WPF エンジンは XAML を解析するときに論理ツリーを構築します。したがって、それぞれMyItem
が の論理的な子である必要がありMyControl
ます。逆に、MyControl
は各 の論理的な親である必要がありますMyItem
。
まあ、どうやらそれ以上のものがあるようです。以下は、上記の関係を定義するために使用するコードです。カスタム コントロールにはDependencyProperty
for が含まれて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
ですか?