【WPF】ListBox使用DataTemplate 以及默认选中第一项Item
WPF 以及 默认 选中 item ListBox 使用
2023-09-11 14:22:26 时间
ListBox中DataTemplate的用法如下 。
<ListBox x:Name="areaLB" ItemsSource="{Binding AreaNumList}" SelectedItem="{Binding SelectedItem}" BorderThickness="0" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton x:Name="radioBtn" FontSize="14" GroupName="area" Style="{StaticResource myRadioButton2}">
<RadioButton.IsChecked>
<Binding Path="IsSelected" RelativeSource="{RelativeSource AncestorType=ListBoxItem}" Mode="TwoWay" />
</RadioButton.IsChecked>
<RadioButton.Content>
<Binding Path="Content" RelativeSource="{RelativeSource AncestorType=ListBoxItem}" Mode="TwoWay" />
</RadioButton.Content>
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
需求:初始化时,使ListBox默认选中第一项。(否则将没有任一项被选中)
过程:由于ListBox使用了DataTemplate,一直是想办法如何去访问/获取到ListBox中的第一项,然后设置该项
RadioButton.isChecked = true;
搜到不少类似下面这种方法的,如何从控件中递归找到子控件,都没法解决问题:
private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
最后才发现,直接把ListBox控件的选中项设为第一项即可!其实就是这么简单!!
listBox1.SelectedIndex = 0;
重要的参考:
http://stackoverflow.com/questions/8221795/selecting-first-item-in-listbox
相关文章
- 使用WPF来创建 Metro UI程序
- WPF一步一脚印系列(1):万事起头难
- 【基于WPF+OneNote+Oracle的中文图片识别系统阶段总结】之篇一:WPF常用知识以及本项目设计总结
- atitit.软件开发GUI 布局管理优缺点总结java swing wpf web html c++ qt php asp.net winform
- WPF Bitmap转imagesource
- WPF中的依赖项属性
- wpf binding
- WPF 自定义绕圈进度条(转)
- WPF Canvas, how to add children dynamically with MVVM code behind
- WPF快速入门系列(8)——MVVM快速入门
- WPF快速入门系列(5)——深入解析WPF命令
- Actipro WPF Controls 22.1.3 -new-注册版
- Neodynamic Barcode Professional for WPF V11.0
- MVVM 模式下 WPF Password 控件的数据绑定解析