c# - WPF/C# - 以编程方式创建和使用单选按钮的示例

标签 c# .net wpf radio-button

有人可以指出如何在 C# WPF 中以编程方式创建和使用单选按钮的示例吗?

所以基本上如何 (a) 以编程方式创建它们,以及 (b) 如何在值更改时捕获触发器,(c) 如何在给定时间获取结果。

也有兴趣了解答案是否也基于绑定(bind)方法的使用。如果数据绑定(bind)是最简单的方法,那么这样的例子会很棒。否则,如果数据绑定(bind)不是必需的最好/最简单的方法,那么基于非数据绑定(bind)的示例会很好。

注意事项:

  • 注意我的父节点 目前是StackPanel,所以一个方面 问题是如何添加 多个 RadioButtons 到一个 StackPanel我猜。

  • 应该指出,我不知道在编译时会有多少个单选按钮,也不知道文本是什么,这将在运行时发现。

  • 它是一个 WPF 应用程序(即桌面,而不是 Web 应用程序)

最佳答案

通常,我们使用 RadioButtons 向用户呈现枚举数据类型。而我们通常做的是使用 ItemsControl 来呈现一组 RadioButton,每个 RadioButton 都绑定(bind)到一个 ViewModel。

下面是我刚刚编写的一个示例应用程序,演示了如何以两种方式使用 RadioButtons:第一种是某种程度上的直接方法(这可能会回答您上面的问题),第二种使用 MVVM 方法。

顺便说一句,这只是我写得很快的东西(是的,我手头有很多时间)所以我不会说这里的所有内容都是完美的做事方式。但我希望这对您有所帮助:

XAML:

<Window x:Class="RadioButtonSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:RadioButtonSample"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <StackPanel x:Name="sp"/>
        <Button x:Name="showChoice" Click="showChoice_Click">Show Choice</Button>

        <StackPanel x:Name="sp2">
            <StackPanel.DataContext>
                <local:ViewModel/>
            </StackPanel.DataContext>
            <ItemsControl x:Name="itemsControl" ItemsSource="{Binding Path=Choices}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <RadioButton IsChecked="{Binding Path=IsChecked}" Content="{Binding Path=Choice}" GroupName="ChoicesGroup"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        <Button x:Name="showChoice2" Click="showChoice2_Click">Show Choice2</Button>
    </StackPanel>
</StackPanel>

代码隐藏:

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.Generic;

namespace RadioButtonSample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //Initialize the first group of radio buttons and add them to the panel.
            foreach (object obj in Enum.GetValues(typeof(ChoicesEnum)))
            {
                RadioButton rb = new RadioButton() { Content = obj, };
                sp.Children.Add(rb);
                rb.Checked += new RoutedEventHandler(rb_Checked);
                rb.Unchecked += new RoutedEventHandler(rb_Unchecked);
            }
        }

        void rb_Unchecked(object sender, RoutedEventArgs e)
        {
            Console.Write((sender as RadioButton).Content.ToString() + " checked.");
        }

        void rb_Checked(object sender, RoutedEventArgs e)
        {
            Console.Write((sender as RadioButton).Content.ToString() + " unchecked.");
        }

        private void showChoice_Click(object sender, RoutedEventArgs e)
        {
            foreach (RadioButton rb in sp.Children)
            {
                if (rb.IsChecked == true)
                {
                    MessageBox.Show(rb.Content.ToString());
                    break;
                }
            }
        }

        private void showChoice2_Click(object sender, RoutedEventArgs e)
        {
            //Show selected choice in the ViewModel.
            ChoiceVM selected = (sp2.DataContext as ViewModel).SelectedChoiceVM;
            if (selected != null)
                MessageBox.Show(selected.Choice.ToString());
        }
    }

    //Test Enum
    public enum ChoicesEnum
    {
        Choice1,
        Choice2,
        Choice3,
    }

    //ViewModel for a single Choice
    public class ChoiceVM : INotifyPropertyChanged
    {
        public ChoicesEnum Choice { get; private set; }
        public ChoiceVM(ChoicesEnum choice)
        {
            this.Choice = choice;
        }

        private bool isChecked;
        public bool IsChecked
        {
            get { return this.isChecked; }
            set
            {
                this.isChecked = value;
                this.OnPropertyChanged("IsChecked");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        #endregion

    }

    //Sample ViewModel containing a list of choices
    //and exposes a property showing the currently selected choice
    public class ViewModel : INotifyPropertyChanged
    {
        public List<ChoiceVM> Choices { get; private set; }
        public ViewModel()
        {
            this.Choices = new List<ChoiceVM>();

            //wrap each choice in a ChoiceVM and add it to the list.
            foreach (var choice in Enum.GetValues(typeof(ChoicesEnum)))
                this.Choices.Add(new ChoiceVM((ChoicesEnum)choice));
        }

        public ChoiceVM SelectedChoiceVM
        {
            get
            {
                ChoiceVM selectedChoice = this.Choices.FirstOrDefault((c) => c.IsChecked == true);
                return selectedChoice;
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        #endregion

    }
}

关于c# - WPF/C# - 以编程方式创建和使用单选按钮的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623689/

相关文章:

c# - 如何从其他类可以使用的外部设置文件创建字典?

c# - System.Drawing.Graphics 中的 IntPtr.Zero 是什么意思

.net - 使用 .NET WebRequest 将文件上传到共享点时出现 409/冲突 HTTP 错误的原因?

c# - 如何使用Container获取绑定(bind)数据?

c# - WPF 绑定(bind) : Set Listbox Item text color based on property

c# - 自定义路由 asp.net mvc 3 问题

c# - 如何使用 Moq 模拟 SqlDataReader - 更新

.net - 如何在VB.NET中设置线条的粗细

c# - 如何防止 SolidColorBrush 对象发生内存泄漏?

c# - 如何将字符串拆分为某些字符而不是拆分为由这些字符组成的字符串?