Skip to main content
 首页 » 编程设计

c#之如何从 WPF 中的多列 ComboBox 中获取所选项目的值

2024年02月24日25grandyang

    <ComboBox Name="ASelect" Width="180" Height="27" SelectedIndex="0" HorizontalContentAlignment="Center" VerticalAlignment="Center" SelectionChanged="ASelect_SelectionChanged"> 
                 <ComboBoxItem HorizontalContentAlignment="Right" VerticalContentAlignment="Center"> 
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"> 
                        <Image Source="a.png" Height="18" Width="22" /> 
                        <Label Content=" "/> 
                    <TextBlock Width="150" Name="All"> All Values</TextBlock> 
                </StackPanel> 
                </ComboBoxItem> 
 
                <ComboBoxItem HorizontalContentAlignment="Left"> 
                    <StackPanel Orientation="Horizontal"> 
                        <Image Source="tick.png" Height="24" Width="24" /> 
                        <TextBlock Width="150"> New Values</TextBlock> 
                    </StackPanel> 
                </ComboBoxItem> 
 
                <ComboBoxItem HorizontalContentAlignment="Left"> 
                    <StackPanel Orientation="Horizontal"> 
                        <Image Source="question.png" Height="24" Width="24" /> 
                        <TextBlock Width="150"> Old Values</TextBlock> 
                    </StackPanel> 
                </ComboBoxItem> 
</ComboBox> 

如何从多列组合框中获取所选项目的值。我想在文本 block 中获取“所有值”的值。我尝试使用下面的代码,但它给出了 stackpanel 作为字符串,

string selectionString = ((ComboBoxItem)ASelect.SelectedItem).Content.ToString(); 

请您参考如下方法:

给它起个名字

        <TextBlock Name="m_txtAllValues" Width="150"> All Values</TextBlock> 

然后

         m_txtAllValues.Text = "yay it does work"; 

更新:抱歉我误会你了:)

您有一个属性 ASelect.SelectedIndex 指示选择了哪一个 所以你可以制作一个 TextBlocks 的列表集合(List 或 Dictionary f.e)并按顺序将你的文本 block (命名)添加到它然后

     string txt = myCollectionOfTextBlocks[ASelect.SelectedIndex];