Access ListBoxItem-Controls in WPF ListBox
在WPF应用程序中,我使用XAML中以下DataTemplate中定义的ItemTemplate创建Listbox:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <DataTemplate x:Key="ListItemTemplate"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <StackPanel> <Button/> <Button/> <Button Name="btnRefresh" IsEnabled="false"/> <TextBlock/> <TextBlock/> <TextBlock/> <TextBlock/> </StackPanel> <TextBox/> </Grid> </DataTemplate> |
一旦生成ListBox,我需要在所有ListBoxItem上将以下按钮IsEnabled属性更改为true:
问题:
我无法访问ListBoxItem,因此无法通过其中的那个按钮访问其子级。
在WPF中是否有类似Silverlight的ListBox.Descendents()之类的东西,或通过任何其他方式到达该按钮,
执行此操作的首选方法是更改??与该Button的IsEnabled属性绑定的
另一个选项,如果需要遍历ListBox中的每个数据模板项,请执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 | if (listBox.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { foreach (var item in listBox.Items) { ListBoxItem container = listBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem; // Get button ContentPresenter contentPresenter = contentPresenter.ContentTemplate.FindName("btnRefresh", contentPresenter); Button btn = contentPresenter as Button; if (btn != null) btn.IsEnabled = true; } } |
如果您只需要启用ListBoxItem中的按钮,则可以使用XAML解决方案。使用DataTemplate.Triggers:
1 2 3 4 5 6 | <DataTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource= {RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"> <Setter TargetName="btnRefresh" Property="IsEnabled" Value="true"/> </DataTrigger> </DataTemplate.Triggers> |
以这种方式,每当ListBoxItem的被选择时,关于该项目的按钮将被激活。不需要c#代码。简单干净。
更多详细信息,请参见:http://wpftutorial.net/DataTemplates.html