繁体   English   中英

如何从WPF列表框中获取选定列表项中的选定单选按钮

[英]How to get selected radio button in selected list item from wpf listbox

列表框的图像如下:

带有复选框的动态列和静态单选按钮的列表框

我必须从列表框中查找选定的项目,并为每个选定的项目选择选定的单选按钮

<ListBox Height="226" HorizontalAlignment="Left" Margin="404,339,0,0" Name="listBoxItems" VerticalAlignment="Top" Width="282" SelectionChanged="listBoxItems_SelectionChanged" SelectionMode="Multiple">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="10,5,0,0">
                        <CheckBox Width="130" x:Name="chbPrescr"  Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}">
                            <!--<TextBlock Text="{Binding}" Width="115"></TextBlock>-->

                        </CheckBox>
                        <RadioButton x:Name="rdOD" Width="40" Content ="OD" Checked="rdOD_Checked" />
                        <RadioButton x:Name="rdBD" Width="40" Content ="BD" Checked="rdBD_Checked"/>
                        <RadioButton x:Name="rdTDS" Width="40" Content ="TDS" Checked="rdTDS_Checked"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

在回发事件中,我得到的是选定列表项,而不是该选定列表项的选定单选按钮

foreach (var items in listBoxItems.SelectedItems)
{ 
    string a = items.ToString();
    ItemCollection itemCollection = listBoxItems.Items;
    object currentItem = itemCollection.CurrentItem;
}

我需要知道如何获取每种所选药物的类别。 谢谢

您可以将RadioButtonsIsChecked属性绑定到数据类的source属性:

WPF + MVVM + RadioButton:具有单个属性的句柄绑定

这是优选的解决方案。

最快的一种可能是在可视树中找到选定的RadioButton

private void listBoxItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (var items in listBoxItems.SelectedItems)
    {
        ListBoxItem lbi = listBoxItems.ItemContainerGenerator.ContainerFromItem(items) as ListBoxItem;
        if (lbi != null)
        {
            RadioButton rb = FindVisualChildren<RadioButton>(lbi).FirstOrDefault(x => x.IsChecked == true);
            if (rb != null)
            {
                MessageBox.Show("selected: " + rb.Content.ToString());
            }
        }
    }
}

private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        int NbChild = VisualTreeHelper.GetChildrenCount(depObj);

        for (int i = 0; i < NbChild; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childNiv2 in FindVisualChildren<T>(child))
            {
                yield return childNiv2;
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM