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

发布于 2024-09-16 19:14:50 字数 418 浏览 6 评论 0原文

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

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

我们也有兴趣看看答案是否也基于使用绑定方法。如果数据绑定是最简单的方法,那么这个例子就很好了。否则,如果数据绑定不是最好/最简单的方法,那么基于非数据绑定的示例会很好。

注意:

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

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

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

Can someone point to an example of how to programmatically create & use Radio Buttons in C# WPF?

So basically how to (a) create them programmatically, and (b) how to catch triggers when the value changes, (c) how to pick up results at a given time.

Will be interested to see too if the answer will be based on use of a Binding approach too. If data binding is the easiest way to go then an example of this would be great. Else if data binding isn't necessary the best/easiest way to go then a non-data-binding based example would be good.

Notes:

  • Note that the parent node I have
    currently is StackPanel, so an aspect
    of the question is how to add
    multiple RadioButtons to a
    StackPanelI guess.

  • Should point out that I won't know how many radio buttons there will be at compile time, nor what the text will be this will be discovered at run time.

  • It is a WPF application (i.e. desktop, not a web app)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若相惜即相离 2024-09-23 19:14:50

通常,我们使用 RadioButtons 向用户呈现 Enum 数据类型。我们通常做的是使用 ItemsControl 来呈现一组 RadioButton,每个 RadioButton 都绑定到一个 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

    }
}

Normally, we use RadioButtons to present an Enum data type to the user. And what we usually do is use an ItemsControl to present a group of RadioButtons, with each one bound to a ViewModel.

Below is a sample application I just wrote that demonstrates how RadioButtons could be used in two ways: the first is somewhat of a direct approach (and this may answer your questions above), and the second one uses an MVVM approach.

BTW, this is just something I wrote quickly (yeah, I got a lot of time in my hands) so I won't say that everything in here is the perfect way of doing things. But I hope you find this helpful:

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>

Code-behind:

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

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文