datatemplate中的单选按钮wpf c#

时间:2016-02-25 10:47:37

标签: c# wpf

我正在尝试访问datatemplate中的数据网格中的单选按钮。我遇到了很多答案,但没有一个适合我。 我在3个不同的列中有3个不同的无线电按钮。我只是想弄清楚如何访问这些单选按钮并杀死我,我已经挣扎了好几天请帮助。

<DataGridTemplateColumn Header="Yes" Width="Auto">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Opacity="0.8">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <RadioButton x:Name="rbYes" GroupName="{Binding QuestionID}" Content="Yes" Grid.Column="0" />
                </Grid>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="No" Width="Auto">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Opacity="0.8">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <RadioButton x:Name="rbNo" GroupName="{Binding QuestionID}" Content="No" Grid.Column="0" />
                </Grid>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="N/A" Width="Auto">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Opacity="0.8">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <RadioButton x:Name="rbNA" GroupName="{Binding QuestionID}" Content="N/A" Grid.Column="0" />
                </Grid>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

这是我背后的代码。我已经改变了很多次。

RadioButton rbYes = (RadioButton)FindName("rbYes");
RadioButton rbNo = (RadioButton)FindName("rbNo");
RadioButton rbNA = (RadioButton)FindName("rbNA");

if (rbYes.IsChecked == true)
{
    rbNo.IsChecked = false;
    rbNA.IsChecked = false;
    int questionID = Convert.ToInt32(drv["QuestionID"]);
    questionAnswer = "Yes".ToString();
    if (drv["Notes"].ToString() == "")
    {
        string notes = null;
    }
    else
    {
        string notes = drv["Notes"].ToString();
    }

2 个答案:

答案 0 :(得分:1)

假设您熟悉数据绑定(因为您已经绑定了QuestionID),我的建议如下:

  1. 在数据网格中填充数据的对象中有3个布尔属性,表示IsYes,IsNo,IsNA。将绑定到datagrid的ItemSource的集合设置为ObservableCollection。
  2. 将单选按钮的IsChecked分别绑定到这三个属性。
  3. 通过执行上述步骤,您不必担心深入数据网格的单元格以查找控件并知道它们是否已设置。

    [更新]抱歉延迟。我在开会。守则如下。 请注意,这是如何实现我上面提到的概念的非常粗略的模拟。

    <强> MainWindow.xaml

    <Window x:Class="testWPFApplication.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:testWPFApplication"
            mc:Ignorable="d" DataContext="{Binding RelativeSource={RelativeSource Self}}"
            Title="MainWindow" Height="350" Width="525">
        <Grid x:Name="LayoutRoot" >
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="30" />
            </Grid.RowDefinitions>
    
            <DataGrid Grid.Row="0" SelectionMode="Single"
                      ItemsSource="{Binding Questions}" SelectedItem="{Binding SelectedQuestion,Mode=TwoWay}" AutoGenerateColumns="False"
                      CanUserAddRows="False" CanUserDeleteRows="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Question Id" Binding="{Binding QuestionId}" IsReadOnly="True" />
                    <DataGridTextColumn Header="Question" Binding="{Binding QuestionDescription}" Width="3*" IsReadOnly="True" />
                    <DataGridTemplateColumn Header="Yes">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <RadioButton GroupName="{Binding QuestionId}" IsChecked="{Binding IsYes, Mode=TwoWay,UpdateSourceTrigger=LostFocus,NotifyOnTargetUpdated=True}" 
                                             HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn Header="No">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <RadioButton GroupName="{Binding QuestionId}" IsChecked="{Binding IsNo, Mode=TwoWay,UpdateSourceTrigger=LostFocus,NotifyOnTargetUpdated=True}" 
                                             HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn Header="N/A">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <RadioButton GroupName="{Binding QuestionId}" IsChecked="{Binding IsNA, Mode=TwoWay,UpdateSourceTrigger=LostFocus,NotifyOnTargetUpdated=True}" 
                                             HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
    
            <Button Grid.Row="1" Width="100" x:Name="btnCheckAnswers" HorizontalAlignment="Right" Margin="5" Click="btnCheckAnswers_Click" Content="Check Answers" />
        </Grid>
    </Window>
    

    MainWindow.xaml.cs (代码隐藏。可以移动不同的ViewModel类)

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    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;
    
    namespace testWPFApplication
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window, INotifyPropertyChanged
        {
            private ObservableCollection<Question> _questions;
            private Question _selectedQuestion;
    
            public ObservableCollection<Question> Questions
            {
                get { return _questions; }
                set
                {
                    _questions = value;
                    OnPropertyChanged("Questions");
                }
            }
    
            public Question SelectedQuestion
            {
                get { return _selectedQuestion; }
                set
                {
                    _selectedQuestion = value;
                    OnPropertyChanged("SelectedQuestion");
                    OnSelectedQuestionChanged();
                }
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            public void OnPropertyChanged(string strPropertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
                }
            }
    
            public MainWindow()
            {
                InitializeComponent();
                DataContext = this;
                Init();
    
            }
    
            private void Init()
            {
                CreateMockData();
            }
    
            private void CreateMockData()
            {
                if (Questions == null)
                {
                    Questions = new ObservableCollection<Question>();
                }
                else
                {
                    Questions.Clear();
                }
    
                for (int i = 1; i <= 5; i++)
                {
                    Question q = new Question
                    {
                        QuestionId = i,
                        QuestionDescription = "Sample Question " + i.ToString(),
                        IsYes = false,
                        IsNA = false,
                        IsNo = false
                    };
                    Questions.Add(q);
                }
            }
    
            private void OnSelectedQuestionChanged()
            {
                if(SelectedQuestion != null)
                {
    
                }
            }
    
            private void btnCheckAnswers_Click(object sender, RoutedEventArgs e)
            {
                StringBuilder strQuestionAnswer = new StringBuilder();
                foreach (Question item in Questions)
                {
                    strQuestionAnswer.AppendLine(item.QuestionDescription + ":");
                    strQuestionAnswer.AppendLine("IsYes:" + item.IsYes);
                    strQuestionAnswer.AppendLine("IsNo:" + item.IsNo);
                    strQuestionAnswer.AppendLine("IsNA:" + item.IsNA);
                }
    
                MessageBox.Show(strQuestionAnswer.ToString());
            }
        }
    
        public class Question
        {
            public int QuestionId { get; set; }
    
            public string QuestionDescription { get; set; }
    
            public bool IsYes { get; set; }
    
            public bool IsNo { get; set; }
    
            public bool IsNA { get; set; }
        }
    }
    

    加载窗口

    Window_load

    设置的值很少

    Few_values_set

    点击按钮时的结果

    result_when_the_button_is_clicked

    希望此示例可以帮助您解决您遇到的问题。

答案 1 :(得分:0)

感谢您的回复。但这不是问题,问题是,我尝试使用无线电按钮,但我可以找到带有FindName功能的按钮。为rbYes,rbNo和rbNA返回Null。我不知道我的解释是否足够好。