【问题标题】:How to set selected item or value for listbox in WPF from code behind?如何从后面的代码中为 WPF 中的列表框设置选定项或值?
【发布时间】:2018-05-02 08:01:44
【问题描述】:

我有列表框,我需要从代码中设置它的选定值。它没有被选中给定值。我正在处理 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";

【问题讨论】:

  • 绑定的 ItemsSource 类型是什么?是 List 吗?
  • 不确定您的意思是“从代码中设置其选定的值”。您的意思是要将 ListItem 从您的代码隐藏添加到您当前的 ListBox 中吗?
  • 我需要从 ListItems 中设置选定的值

标签: c# asp.net wpf listbox


【解决方案1】:

这对我有用。

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

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多