シェイプを含むコレクションにItemsControlをバインドする際に問題があります。私はDataTemplateは必要ありませんが、コレクションに含まれるアイテムのTop/Left位置を指定したいと思います。シェイプアイテムでItemsControlの左上座標を指定する
<ItemsControl x:Name="regions" DataContext="{Binding Path=Model}" ItemsSource="{Binding Path=Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas x:Name="canvas" Background="Yellow" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
public Model Model {get;}
public class Model : INotifyPropertyChanged
{
public ObservableCollection<Element> Items {get;}
}
public class Element : Shape
{
public override System.Windows.Media.Geometry Geometry {get;}
}
私はItemsControl.ItemContainerStyleを使用してみましたが、私はこのバインディングエラーを得た:
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding Geometry.Bounds.Left}" />
<Setter Property="Canvas.Top" Value="{Binding Geometry.Bounds.Top}" />
</Style>
</ItemsControl.ItemContainerStyle>
System.Windows.Data Error: 40 : BindingExpression path error: 'Geometry' property not found on 'object' ''Model' (HashCode=41545796)'. BindingExpression:Path=Geometry.Bounds.Top; DataItem='Model' (HashCode=41545796); target element is 'Element' (Name=''); target property is 'Top' (type 'Double')
ジオメトリプロパティではなく要素よりも、モデルに適用されているように見えます。
私はデバッグの目的のためにコンバータを追加しました:私はDebugConverterにブレークポイントを設定すると
<Setter Property="Canvas.Left" Value="{Binding ., Converter={StaticResource debugConverter}}" />
、「オブジェクト」に渡されたタイプのモデルではなく、要素のです。これは間違っているようだ、私はそれが要素であると期待するだろう。どのように要素を取得するのですか?
あなたのデータアイテムクラスは何らかの理由でElementではなくModelです(バインディングエラーメッセージの 'DataItem = 'Model''を参照)。これはここに表示されているコードには対応していません。 – Clemens
それに加えて、 'public Model Model = new Model();'は 'DataContext =" {Binding Path = Model} "に必要なプロパティを宣言しません。そのDataContext宣言を削除し、代わりに ' 'を試してください。 –
Clemens
実際、WPFのスタイルは実際のDataContextについてはわかりませんし、変更する方法もありません。だから、そのエラーを無視してください。スタイルは大丈夫です。 'Value =" {Binding(Element.Geometry).Bounds.Left} "' – cdmnk