![](/img/trans.png)
[英]Setting Canvas Children Property without ItemsControl ItemsSource Binding Property
[英]Canvas Children Property Binding
我正在學習 wpf 以及如何正確綁定。 這是我正在處理的代碼:
<ItemsControl ItemsSource="{Binding CanvasChildren}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type espace:Entity}" />
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}" />
<Setter Property="Canvas.ZIndex" Value="{Binding Z}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
所以你可以看到我在這個ItemsControl
中綁定CanvasChildren
。 CanvasChildren
是一個“ Entity
”類型的ObservableCollection
。 Entity
是我自己的 class,它是另一個canvas
object,其中包含圖像等。
Entity
在其中具有屬性X
、 Y
、 Z
,我希望能夠將這些屬性綁定到Canvas.Left
、 Canvas.Top
、 Canvas.ZIndex
但我完全不知道該怎么做。 我在這里定義的樣式設置器不起作用。
其中一個綁定值正在檢查我定義的視圖模型中的 X、Y、Z 坐標:
<base:SceneBase.DataContext>
<sceneGame:SceneGameViewModel />
</base:SceneBase.DataContext>
但是將設置器更改為:
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type espace:Entity}}, Path=X}" />
<Setter Property="Canvas.Top" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type espace:Entity}}, Path=Y}" />
<Setter Property="Canvas.ZIndex" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type espace:Entity}}, Path=Z}" />
</Style>
</ItemsControl.ItemContainerStyle>
也不起作用。
我可能忽略了一些簡單的事情,但我仍在學習 WPF 並且我迷路了。
如果您使用帶有UIElement
項目類型的 ItemsControl(這有點不尋常),該控件將不會為其創建額外的項目容器(即 ContentPresenter)元素,而是直接將 ItemContainerStyle 應用於該項目。 您可以通過在樣式上設置TargetType="espace:Entity"
來驗證這一點。
在這種情況下,ItemsControl 也不會設置 UIElement 項的 DataContext,這意味着沒有顯式設置源的綁定將不起作用。 ItemContainerStyle 中的綁定將直接使用項目 object 作為其來源,即使用RelativeSource Self
。
為項類型(尤其是空項)聲明 DataTemplate 也是無用的,因為它會被忽略。 該項目不被視為“數據”,而是 UI。
<ItemsControl ItemsSource="{Binding CanvasChildren}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="espace:Entity">
<Setter
Property="Canvas.Left"
Value="{Binding X, RelativeSource={RelativeSource Self}}"/>
<Setter
Property="Canvas.Top"
Value="{Binding Y, RelativeSource={RelativeSource Self}}"/>
<Setter
Property="Panel.ZIndex"
Value="{Binding Z, RelativeSource={RelativeSource Self}}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.