簡體   English   中英

如何從后面的代碼設置WPF中列表框的選定項目或值?

[英]How to set selected item or value for listbox in WPF from code behind?

我有列表框,我需要從代碼中設置其選定的值。 它沒有被選擇給定的值。我正在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”都是同一對象。 對於更復雜的對象,我需要獲取對特定實例的引用或重寫類中的equals。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM