WPF获取窗体元素

获取窗体上面所有CheckBox选中的Content值。

xaml:

 <StackPanel>
        <CheckBox Content="a" IsChecked="True"/>
        <CheckBox Content="b"/>
        <CheckBox Content="c" IsChecked="True"/>
        <CheckBox Content="d"/>
        <CheckBox Content="e" IsChecked="True"/>
        <CheckBox Content="f"/>
        <Button Content="Show" Width="60" Click="Button_Click"></Button>
    </StackPanel>

cs:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            StackPanel sp = this.Content as StackPanel;
            UIElementCollection children = sp.Children;
            foreach (UIElement ui in children)
            {
                if (ui is CheckBox)
                {
                    CheckBox cb = ui as CheckBox;
                    if (cb.IsChecked == true)
                    {
                        MessageBox.Show(cb.Content.ToString());
                    }
                }
            }
        }

原文地址:https://www.cnblogs.com/KimhillZhang/p/2407313.html