c# - 如何从后面的代码中为 WPF 中的列表框设置选定项或值?
问题描述
我有列表框,我需要从代码中设置它的选定值。它没有被选中给定值。我正在处理 WPF 应用程序。请帮我写代码。以下是我的代码:
<ListBox x:Name="lbCheque" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,191,0,0"
Width="200" Height="210" SelectionChanged="lbCheque_SelectionChanged" >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
后面的代码:
lbCheque.SelectedItem = "abcd";
解决方案
这对我有用。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<ListBox x:Name="lbCheque" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,191,0,0"
Width="200" Height="210" >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<Button
Grid.Column="1"
Content="Select"
Click="Button_Click"/>
</Grid>
</Window>
和
public MainWindow()
{
InitializeComponent();
lbCheque.ItemsSource = new List<string> {"aa","bb","cc" };
}
private void Button_Click(object sender, RoutedEventArgs e)
{
lbCheque.SelectedItem = "bb";
}
这依赖于字符串有点奇怪并且所有字符串“bb”都是同一个对象的事实。对于更复杂的对象,我需要获取对特定实例的引用或覆盖类中的等于。
推荐阅读
- java - 将 Java 8 升级到 Java 11 是否有效?
- tfs - 在没有服务器端工作的情况下将 VS2019 与 TFS2018 vnext 构建系统一起使用
- python - 保留单词数组中刚刚给定的单词来自另一个数组
- python-3.x - 没有名为 cmake 的模块
- python - python kivy 如何将我的文本文件保存到内部存储中(文件管理器)
- javascript - 如何显示多个对象值值 mat-option 或将多个值绑定到 mat-option 的 [value] 属性
- netbeans - 从 Netbeans 中的特定文件中排除 TODO
- python - 获取具有另一个数据框条件的数据框列的最小值
- css - Gatsby 如何在 scss 中正确导入 svg 作为背景?
- javascript - 如何使用来自 node.js 的参数调用 .exe 文件