【发布时间】:2019-07-04 21:13:14
【问题描述】:
我将 ListBox 与 ObservableCollection 结合使用。内容通过 TemplateSelector(TextBlock 或 Label)设置。文本必须格式化(例如,在代码隐藏中使用运行标签),但我无法访问项目。有没有办法获取元素?
我尝试过使用 OfType,但这仅适用于面板。我搜索了一个儿童属性,但是没有一个用于 ListBoxes 的属性。 UId 和 Name 无法通过绑定设置 Name-Property。 LogicalChildren 的 IEnumerator 不起作用,并且每次添加新元素时都会遍历整个内容,并不是那么理想。这是一个最小的例子。
<Window.Resources>
<DataTemplate x:Key="TextBlockTemplate">
<StackPanel>
<TextBlock />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="LabelTemplate">
<StackPanel>
<Label/>
</StackPanel>
</DataTemplate>
<local:myTemplateSelector x:Key="myTemplateSelector" x:Name="myTemplateSelector" TextBlockTemplate="{StaticResource TextBlockTemplate}" LabelTemplate="{StaticResource LabelTemplate}"/>
</Window.Resources>
<Grid Margin="0">
<ListBox Name="mylist" Grid.Row="3"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding _listEntries}"
ItemTemplateSelector="{StaticResource myTemplateSelector}"
>
</ListBox>
</Grid>
问候和感谢 :)
【问题讨论】: