在具有Canvas ItemsPanel的ListBox的上下文中,我需要爲多個DataTemplates中的每個控件(該列表顯示幾個對象類型)訪問Cavas.ZIndex。它不足以使用從DataTemplate訪問ItemsPanel屬性
<ListBox.ItemContainerStyle>
<Setter Property="Canvas.ZIndex" ..... />
因爲有幾個數據模板,每個都有幾個控件,我想控制每個控件的絕對zindex。 這甚至可能嗎?
在具有Canvas ItemsPanel的ListBox的上下文中,我需要爲多個DataTemplates中的每個控件(該列表顯示幾個對象類型)訪問Cavas.ZIndex。它不足以使用從DataTemplate訪問ItemsPanel屬性
<ListBox.ItemContainerStyle>
<Setter Property="Canvas.ZIndex" ..... />
因爲有幾個數據模板,每個都有幾個控件,我想控制每個控件的絕對zindex。 這甚至可能嗎?
據我所知,這是不可能的
的原因是,當一個列表框渲染,它呈現像這樣(假設你指的是你在your other question有相同的代碼):
<Canvas>
<ListBoxItem>
<ContentPresenter>
<Grid>
<TextBlock />
<Line />
</Grid>
</ContentPresenter>
</ListBoxItem>
<ListBoxItem>
<ContentPresenter>
<Grid>
<TextBlock />
<Line />
</Grid>
</ContentPresenter>
</ListBoxItem>
<ListBoxItem>
<ContentPresenter>
<Grid>
<TextBlock />
<Line />
</Grid>
</ContentPresenter>
</ListBoxItem>
...
</Canvas>
如您所見,每個ListBoxItem都呈現爲一組嵌套控件。您不能將所有TextBlocks繪製在所有行的頂部,因爲它們不共享同一個父級,並且ZIndex用於對同一父級容器內的項目進行排序。
解決方法是使用兩個單獨的ItemsControl,彼此重疊。因此,所有的線條都將繪製在Bottom ItemsControl上,而所有TextBlocks都將繪製在Top ItemsControl上。
<Grid>
<ItemsControl ItemsSource="{Binding MyData}"
ItemTemplate="{DynamicResource MyLineTemplate}" />
<ItemsControl ItemsSource="{Binding MyData}"
ItemTemplate="{DynamicResource MyTextBlockTemplate}" />
</Grid>
任何人都可以確認這是不可能的嗎? – Ricibob
這是WPF的缺陷。你可以通過幾行XAML來完成一些複雜的東西 - 但是然後像設置一個absolution z-order這樣的簡單事情就變成了一次巨大的考驗... – Ricibob