我有列表框,我需要从代码中设置其选定的值。它没有被选中给定的值。我正在研究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";
答案 0 :(得分:0)
这对我有用。
<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";
}
这取决于字符串有点奇怪且所有字符串&#34; bb&#34;是同一个对象。对于更复杂的对象,我需要获得对特定实例的引用或在类中重写equals。