首页 > 解决方案 > Listbox WPF C#中的SelectedItem事件

问题描述

我想在ListBox中选中RadioButton时捕获一个事件,我正在尝试使用 selectionChanged 事件,但它被延迟了,而且没有效果。有没有其他方法可以做到这一点?非常感谢!

<ListBox SelectionChanged="lstPlotter_SelectionChanged_1" x:Name="lstPlotter"  Style="{StaticResource 0009}">
    <RadioButton Content="DWG To PDF.pc3" Style="{StaticResource 0004}" IsChecked="True"/>
    <RadioButton Content="AutoCAD PDF (High Quality Print).pc3" Style="{StaticResource 0004}"/>
    <RadioButton Content="AutoCAD PDF (General Documentation).pc3" Style="{StaticResource 0004}"/>
    <RadioButton Content="AutoCAD PDF (Smallest File).pc3" Style="{StaticResource 0004}"/>
    <RadioButton Content="AutoCAD PDF (Web and Mobile).pc3" Style="{StaticResource 0004}"/>
</ListBox>

标签: c#wpfeventslistbox

解决方案


我强烈建议您学习如何分离数据及其表示(视图)。WPF 的整个概念都是围绕这种分离构建的。
如果不将它们分开,您就会为自己制造许多问题。

在此任务中,您的数据是 RadioButton.Content 中包含的字符串集合。
此字符串集合必须传递给 ListBox 源。
在 ListBox 项的模板中,您需要从源中传递集合项的数据模板。
也就是说,对于这种情况,对于字符串。
在这个数据模板中,您需要设置一个 RadioButton 来表示集合中的一个字符串。
RadioButton 必须绑定到包含 ListBoxItem 的 IsSelected 属性。

    <UniformGrid Background="AliceBlue" Columns="1">
        <FrameworkElement.Resources>
            <Style x:Key="0004"/>
            <Style x:Key="0009"/>
            <spec:StringCollection x:Key="ListBox.SourceItem">
                <sys:String>DWG To PDF.pc3</sys:String>
                <sys:String>AutoCAD PDF (High Quality Print).pc3</sys:String>
                <sys:String>AutoCAD PDF (General Documentation).pc3</sys:String>
                <sys:String>AutoCAD PDF (Smallest File).pc3</sys:String>
                <sys:String>AutoCAD PDF (Web and Mobile).pc3</sys:String>
            </spec:StringCollection>
            <DataTemplate x:Key="ListBox.ItemTemplate"
                          DataType="{x:Type sys:String}">
                <RadioButton GroupName="_listBox"
                             Content="{Binding}"
                             IsChecked="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}}"
                             Style="{DynamicResource 0004}"/>
            </DataTemplate>
        </FrameworkElement.Resources>
        <TextBlock x:Name="tBlock"/>
        <ListBox x:Name="lstPlotter"
                 SelectionChanged="lstPlotter_SelectionChanged_1"
                 Style="{DynamicResource 0009}"
                 ItemTemplate="{DynamicResource ListBox.ItemTemplate}"
                 ItemsSource="{DynamicResource ListBox.SourceItem}"
                 SelectedIndex="0"
                 SelectionMode="Single"/>
    </UniformGrid>
        private void lstPlotter_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
                tBlock.Text = ((ListBox)sender).SelectedItem?.ToString();
        }

推荐阅读