如何更改 RadioButton 内容?

How can I change RadioButton content?

我有一个问题要问你。我想将我的 WPF 应用程序设置为仅将我的 RadioButton 更改为他们自己的 content.I正在尝试创建一个数学测验,用户可以在其中选择三个选项之一。

我试过这个:

List<string> list = new List<string> { "1", "2", "3" };//is there any way to add those options here?
        public void ShuffleText()
        {
            var rand = new Random();
            var shuffledText = list.OrderBy(x => rand.Next(list.Count)).ToList();
            var radioButtons = new[] { firstOption, secondOption, thirdOption };

            for (int i = 0; i < radioButtons.Length; i++)
            {
                radioButtons[i].Content = shuffledText[i];
            }
        }

        private void control_Click(object sender, RoutedEventArgs e)
        {

            timer.Value += 1;
            shiftTimer.Start();
            if (vybOp == 0 || vybOp == 2 || vybOp == 4 || vybOp == 6)//this is enumeration selected operations
            {
                var answerRadioButtons = new RadioButton[] { firstOption, secondOption, thirdOption };
                var correctAnswerButtonFound = false;
                foreach (var answerButton in answerRadioButtons)
                {
                    if (answerButton.IsChecked==true)
                    {

                        if (answerButton.Content == result.Text)
                        {

                            correctAnswerButtonFound = true;
                        }
                    }
                }

                if (correctAnswerButtonFound)
                {
                    shiftTimer.Stop();
                    call.Text = "Correct";
                    count++;
                    numberOfExamples.Text = count.ToString();
                    Random second = new Random();
                    Random first = new Random();

                    int maxFirst = 10;
                    int maxSecond = 10;


                    int secondN = second.Next(2, maxSecond);
                    int firstN = secondN * first.Next(1, maxFirst / secondN);
                    if (mark.Text == "+")
                    {
                        int total = (firstN + secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();

                    }
                     if (mark.Text == "-")
                    {
                        int total = (firstN - secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();

                    }
                     if (mark.Text == "*")
                    {
                        int total = (firstN * secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();

                    }
                     if (mark.Text == "/")
                    {
                        int residue = (firstN % secondN);
                        if (residue == 0)
                        {
                           int total = (firstN / secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();
                        }


                    }


                    timer.Value = 0;
                    shiftTimer.Start();
                }

                else
                {
                    shiftTimer.Stop();
                    call.Text = "Wrong";
                    poch++;//number of error
                    count++;
                    numberOfError.Text = poch.ToString();
                    numberOfExample.Text = count.ToString();
                    Random second = new Random();
                    Random first = new Random();

                   int maxFirst = 10;
                    int maxSecond = 10;


                    int secondN = second.Next(2, maxSecond);
                    int firstN = secondN * first.Next(1, maxFirst / secondN);
                   if (mark.Text == "+")
                    {
                        int total = (firstN + secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();

                    }
                    if (mark.Text == "-")
                    {
                        int total = (firstN - secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();

                    }
                     if (mark.Text == "*")
                    {
                        int total = (firstN * secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();

                    }
                    if (zmark.Text == "/")
                    {
                        int residue = (firstN % secondN);
                        if (residue == 0)
                        {
                           int total = (firstN / secondN);
                        firstT.Text = firstN.ToString();
                        secondT.Text = secondN.ToString();
                        result.Text = total.ToString();
                        }

                    }
                }


                timer.Value = 0;
                shiftTimer.Start();
                if (poch == 4)
                {
                    mt.Stop();
                    timer.Value = 0;
                    shiftTimer.Stop();
                    MessageBox.Show("Game Over!");
                    end_Click(sender, e);








                }
            }

我更愿意将整个代码发送到这里,以免遗漏任何内容(是的,它写得不好,但也许可以使用)。我的问题是我想给Radiobutton(firstOption, secondOption, thirdOption)赋值给它们的内容,这样一来就正确了。我会根据个别例子中的标记来赋值(例如

if (mark.Text == "+")
                   {
                       int total = (firstN + secondN);
                       firstT.Text = firstN.ToString();
                       secondT.Text = secondN.ToString();
                       result.Text = total.ToString();

                   }

但我不知道如何分配它。

如果有人有任何问题,请在评论中写信给我,对于语言的组合,我深表歉意。我希望我的意思至少有点明显。

谢谢大家的建议。

Update at 2021 05 13

在 WPF 中非常容易

MainWindow.xaml

<Window x:Class="WPFMvvmProjectTemplate1.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:viewModels="clr-namespace:WPFMvvmProjectTemplate1.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <viewModels:MainWindowViewModel/>
    </Window.DataContext>
    <UniformGrid  Columns="4">
        <UniformGrid.Resources>
            <Style TargetType="Button">
                <Setter Property="HorizontalAlignment" Value="Center"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
            </Style>
        </UniformGrid.Resources>

        <ListBox ItemsSource="{Binding QuizTypes, Mode=OneTime}" SelectedItem="{Binding SelectedQuizType, Mode=TwoWay}"/>

        <Button Content="Start" Command="{Binding StartCommand, Mode=OneTime}"/>

        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition/>
            </Grid.RowDefinitions>

            <TextBlock Margin="20" Text="{Binding Quiz, Mode=OneWay}"/>

            <ListBox Grid.Row="1" Margin="10" ItemsSource="{Binding OptionView}">
                <ListBox.ItemTemplate>
                    <!--Data template show you want by data-->
                    <!--OptionView item type-->
                    <DataTemplate DataType="{x:Type viewModels:OptionViewModel}">
                        <RadioButton GroupName="Answer" Content="{Binding Answer, Mode=OneTime}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>

        <Button Content="Answer" Command="{Binding AnswerCommand, Mode=OneTime}"/>
    </UniformGrid>
</Window>

MainWindowViewModel.cs

重要!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Data;
using WPFMvvmProjectTemplate1.Commands;

namespace WPFMvvmProjectTemplate1.ViewModels
{
    enum QuizTypeEnum
    {
        Add,
        Sub,
        Mul,
        Div,
    }

    class OptionViewModel : NotifyPropertyChangedBase
    {
        private int answer;

        public int Answer
        {
            get { return this.answer; }
            set { SetProperty(ref this.answer, value); }
        }


        private bool isSelected;

        public bool IsSelected
        {
            get { return this.isSelected; }
            set { SetProperty(ref this.isSelected, value); }
        }
    }

    class MainWindowViewModel : NotifyPropertyChangedBase
    {
        /// <summary>
        /// command can handl some thing happend
        /// </summary>
        public RelayCommand StartCommand { get; }
        public RelayCommand AnswerCommand { get; }

        public QuizTypeEnum[] QuizTypes { get; } = new QuizTypeEnum[]
            {
                QuizTypeEnum.Add,
                QuizTypeEnum.Sub,
                QuizTypeEnum.Mul,
                QuizTypeEnum.Div,
            };

        private QuizTypeEnum selectedQuizType;

        public QuizTypeEnum SelectedQuizType
        {
            get { return this.selectedQuizType; }
            set { SetProperty(ref this.selectedQuizType, value); }
        }


        private bool isStarted;

        public bool IsStarted
        {
            get { return this.isStarted; }
            set 
            {
                //if changed than return true 
                if (SetProperty(ref this.isStarted, value))
                {
                    //Change can execute state
                    StartCommand.RaiseCanExecuteChanged();
                    AnswerCommand.RaiseCanExecuteChanged();
                }
            }
        }


        private ICollectionView optionView;
        /// <summary>
        /// CollectionView will be "options"
        /// </summary>
        public ICollectionView OptionView
        {
            get { return this.optionView; }
            set { SetProperty(ref this.optionView, value); }
        }

        private string quiz;
        /// <summary>
        /// Quiz
        /// </summary>
        public string Quiz
        {
            get { return this.quiz; }
            set { SetProperty(ref this.quiz, value); }
        }

        public MainWindowViewModel()
        {
            StartCommand = new RelayCommand(OnStartCommandExecute, CanStartCommandExecute);
            AnswerCommand = new RelayCommand(OnAnswerCommandExecute, CanAnswerCommandExecute);
        }

        private bool CanAnswerCommandExecute()
        {
            return IsStarted;
        }

        private void OnAnswerCommandExecute()
        {
            IsStarted = false;

            /*
             To Do ....
             */
            OptionViewModel selected = OptionView.SourceCollection.OfType<OptionViewModel>().Where(x => x.IsSelected).First();

            int answer = selected.Answer;
        }

        private bool CanStartCommandExecute()
        {
            return !IsStarted;
        }

        private void OnStartCommandExecute()
        {
            bool start = true;
            Random first = new Random();
            Random second = new Random();
            int maxFirst = 10;
            int maxSecond = 10;
            int secondN = second.Next(2, maxSecond);
            int firstN = secondN * first.Next(1, maxFirst / secondN);
            List<int> optionList = new List<int>();

            optionList.Add(firstN);
            optionList.Add(secondN);

            switch (SelectedQuizType)
            {
                case QuizTypeEnum.Add:
                {
                    int total = ( firstN + secondN );
                    optionList.Add(total);

                    Quiz = $"{firstN} + {secondN} = ?";
                }
                break;
                case QuizTypeEnum.Sub:
                {
                    int total = ( firstN - secondN );
                    optionList.Add(total);
                    Quiz = $"{firstN} - {secondN} = ?";
                }
                break;
                case QuizTypeEnum.Mul:
                {
                    int total = ( firstN * secondN );
                    optionList.Add(total);
                    Quiz = $"{firstN} * {secondN} = ?";
                }
                break;
                case QuizTypeEnum.Div:
                {
                    int residue = ( firstN % secondN );
                    if (residue == 0)
                    {
                        int total = ( firstN / secondN );
                        optionList.Add(total);
                        Quiz = $"{firstN} / {secondN} = ?";
                    }
                    else
                    {
                        start = false;
                    }
                }
                break;
                default:
                    start = false;
                    break;
            }

            if (start)
            {
                IsStarted = true;

                Random rand = new Random();

                OptionViewModel[] optionViewModels = new OptionViewModel[optionList.Count];
                int index = 0;
                foreach (var item in optionList.OrderBy(x => rand.Next(optionList.Count)))
                {
                    optionViewModels[index] = new OptionViewModel() { Answer = item };
                    index++;
                }
                //show
                OptionView = CollectionViewSource.GetDefaultView(optionViewModels);
            }
            else
            {
                Quiz = string.Empty;
                OptionView = null;
            }
        }
    }
}

MainWindow.xaml.cs

using System.Windows;

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

RelayCommand.cs

using System;
using System.Windows.Input;

namespace WPFMvvmProjectTemplate1.Commands
{
    public class RelayCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        private readonly Func<bool> canExecute;
        private readonly Action execute;
        private readonly EventArgs eventArgs = new EventArgs();
        public RelayCommand(Action execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException(nameof(execute));
            }
            this.execute = execute;
            this.canExecute = canExecute;
        }

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged.Invoke(this, this.eventArgs);
            }
        }

        public bool CanExecute(object parameter)
        {
            return this.canExecute == null ? true : this.canExecute();
        }

        public void Execute(object parameter)
        {
            this.execute();
        }
    }

    public class RelayCommand<T> : ICommand
    {
        public event EventHandler CanExecuteChanged;
        private readonly Func<T, bool> canExecute;
        private readonly Action<T> execute;
        private readonly EventArgs eventArgs = new EventArgs();
        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException(nameof(execute));
            }
            this.execute = execute;
            this.canExecute = canExecute;
        }

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged.Invoke(this, this.eventArgs);
            }
        }

        public bool CanExecute(object parameter)
        {
            if (this.canExecute == null)
            {
                return true;
            }
            else
            {
                if (parameter is T t)
                {
                    return this.canExecute(t);
                }
                else
                {
                    return this.canExecute(default(T));
                }
            }
        }

        public void Execute(object parameter)
        {
            if (parameter is T t)
            {
                this.execute(t);
            }
            else
            {
                this.execute(default(T));
            }
        }
    }
}

NotifyPropertyChangedBase.cs

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WPFMvvmProjectTemplate1.ViewModels
{
    /// <summary>
    /// INotifyPropertyChanged let view can update when you property changed
    /// </summary>
    public class NotifyPropertyChangedBase : INotifyPropertyChanged
    {
        /// <summary>
        /// binding will watch this event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T oldValue, T newValue, [CallerMemberName] string propertyName = "")
        {
            if (oldValue == null)
            {
                if (newValue == null)
                {
                    return false;
                }
                else
                {
                    oldValue = newValue;
                    RaisePropertyChanged(propertyName);
                    return true;
                }
            }
            else
            {
                if (EqualityComparer<T>.Default.Equals(oldValue, newValue))
                {
                    return false;
                }
                oldValue = newValue;
                RaisePropertyChanged(propertyName);
                return true;
            }
        }

        protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
            {
                if (!string.IsNullOrEmpty(propertyName))
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    }
}

欢迎使用 MVVM