Как обращаться с большим количеством радиокнопок с чистым кодом? - PullRequest
0 голосов
/ 30 января 2019

На странице много групп радиокнопок, и когда вы нажимаете на первую, вы добавляете одну в строку и так далее.Если группа радиокнопок не имеет возможности щелкнуть мышью, появится диалоговое окно ref Как мне изменить этот сложный фрагмент кода complex

        if (a121.IsChecked == true) { all1 += "1"; }
else    if (a122.IsChecked == true) { all1 += "2"; }
else    if (a123.IsChecked == true) { all1 += "3"; }
else    if (a124.IsChecked == true) { all1 += "4"; }
else    if (a125.IsChecked == true) { all1 += "5"; }
else
        { MessageBox.Show("An option is not selected"); }

        if (a131.IsChecked == true) { all1 += "1"; }
else    if (a132.IsChecked == true) { all1 += "2"; }
else    if (a133.IsChecked == true) { all1 += "3"; }
else    if (a134.IsChecked == true) { all1 += "4"; }
else    if (a135.IsChecked == true) { all1 += "5"; }
else
        { MessageBox.Show("An option is not selected"); }

        if (a141.IsChecked == true) { all1 += "1"; }
else    if (a142.IsChecked == true) { all1 += "2"; }
else    if (a143.IsChecked == true) { all1 += "3"; }
else    if (a144.IsChecked == true) { all1 += "4"; }
else    if (a145.IsChecked == true) { all1 += "5"; }
else
        { MessageBox.Show("An option is not selected"); }

Ответы [ 2 ]

0 голосов
/ 30 января 2019

Это не самое привлекательное решение, но использует некоторые лучшие методы из WPF, такие как MultiBinding и Converters.В решении используется меньше RadioButtons, но его можно изменить просто.

Страница XAML

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

  <Label Margin="20">
     <Label.Content>
        <MultiBinding Converter="{StaticResource RadioButtonCustomStringConverter}">
           <Binding ElementName="i1r1" Path="IsChecked"/>
           <Binding ElementName="i1r2" Path="IsChecked"/>
           <Binding ElementName="i1r3" Path="IsChecked"/>
           <Binding ElementName="i2r1" Path="IsChecked"/>
           <Binding ElementName="i2r2" Path="IsChecked"/>
           <Binding ElementName="i2r3" Path="IsChecked"/>
           <Binding ElementName="i3r1" Path="IsChecked"/>
           <Binding ElementName="i3r2" Path="IsChecked"/>
           <Binding ElementName="i3r3" Path="IsChecked"/>
        </MultiBinding>
     </Label.Content>
  </Label>

  <StackPanel Grid.Row="1" Margin="20">
     <RadioButton x:Name="i1r1" GroupName="group1" Content="Option1"/>
     <RadioButton x:Name="i1r2" GroupName="group1" Content="Option2"/>
     <RadioButton x:Name="i1r3" GroupName="group1" Content="Option3"/>
  </StackPanel>

  <StackPanel Grid.Row="2" Margin="20">
     <RadioButton x:Name="i2r1" GroupName="group2" Content="Option1"/>
     <RadioButton x:Name="i2r2" GroupName="group2" Content="Option2"/>
     <RadioButton x:Name="i2r3" GroupName="group2" Content="Option3"/>
  </StackPanel>

  <StackPanel Grid.Row="3" Margin="20">
     <RadioButton x:Name="i3r1" GroupName="group3" Content="Option1"/>
     <RadioButton x:Name="i3r2" GroupName="group3" Content="Option2"/>
     <RadioButton x:Name="i3r3" GroupName="group3" Content="Option3"/>
  </StackPanel>
</Grid>

Конвертер

using System;
using System.Globalization;
using System.Windows.Data;
namespace WpfApplication2
{
    public class RadioButtonCustomStringConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if(values != null)
            {
                var result = "";
                for (int i = 0; i < values.Length; i++)
                    if (values[i] as bool? == true)
                        result += (i % 3);

                if (result.Length < 3)
                    return "You haven't selected three items.";
                else
                    return result;
            }
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
0 голосов
/ 30 января 2019

Вы можете определить следующий метод для обработки группы кнопок:

private void AddOrMessage(RadioButton[] radioButtons)
{
    for (int i = 0; i < radioButtons.Length; i++)
    {
        if (radioButtons[i].IsChecked == true)
        {
            all1 += $"{i + 1}";
            return;
        }
    }

    MessageBox.Show("An option is not selected");
}

Затем используйте его следующим образом:

AddOrMessage(new [] {a121, a122, a123, a124, a125});
AddOrMessage(new [] {a131, a132, a133, a134, a135});
AddOrMessage(new [] {a141, a142, a143, a144, a145});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...