首页 > 解决方案 > 如何从后面的代码中为 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";

标签: c#asp.netwpflistbox

解决方案


这对我有用。

    <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”都是同一个对象的事实。对于更复杂的对象,我需要获取对特定实例的引用或覆盖类中的等于。


推荐阅读