【问题标题】:How to implement yes-no radiobuttons in a listview (WPF)?如何在列表视图(WPF)中实现是-否单选按钮?
【发布时间】:2020-01-11 03:50:11
【问题描述】:

我有一个列表视图,其中有一个问题字段和两个单选按钮 - 是和否。我想将每个问题的响应添加到数据库中。我无法这样做。

这是我尝试过的-

部分 XAML 代码(列表视图位于堆栈面板内)-

<ListView HorizontalAlignment="Left" x:Name="listviewQue" Background="Azure" 
         ItemsSource="{Binding Questions}" ScrollViewer.CanContentScroll="False" SelectionMode="Multiple">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <DockPanel>
                        <TextBlock DockPanel.Dock="Top" x:Name="quebox" Text="{Binding que_text}"
                 Style="{StaticResource ResourceKey=textblock_style }" />
                        <RadioButton GroupName="answergrp" Click="Yesradiobtn_Click" x:Name="yesradiobtn" DockPanel.Dock="Left">yes</RadioButton>
                        <RadioButton GroupName="answergrp" Click="Noradiobtn_Click" x:Name="noradiobtn" DockPanel.Dock="Right">no</RadioButton>
                    </DockPanel>


                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>

后面的代码:

private void Yesradiobtn_Click(object sender, RoutedEventArgs e)
        {
            string ans = "yes";
            Question q = new Question();
            q = listviewQue.SelectedItem as Question;
            string res = SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, q.que_id, ans);
            if (!(res == SQLiteDataAccess.SUCCESS))
            {
                MessageBox.Show("SQLite Exception for 'yes' radiobutton click " + res);
            }
        }

        private void Noradiobtn_Click(object sender, RoutedEventArgs e)
        {
            string ans = "no";
            Question q = new Question();
            q = listviewQue.SelectedItem as Question;
            string res = SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, q.que_id, ans);
            if (!(res == SQLiteDataAccess.SUCCESS))
            {
                MessageBox.Show("SQLite Exception for 'no' radiobutton click : " + res);
            }
        }

这是用于插入数据库的sqlite函数:

public static string AddResponse(string sid,string eid,int qid,string answer)
        {
            try
            {
                using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
                {
                    cnn.Execute("insert into RESPONSE values ('" + sid + "','" + eid + "'," + qid + ",'" + answer + "')");
                }
                return SUCCESS;
            }
            catch(Exception e)
            {
                return FAILURE +": exception e = "+e;
            }
        }

我得到的异常消息是 -

\System.NullReferenceException: 'Object reference not set to an instance of an object.'

q was null.

我怎样才能实现它?

更新问题类 -

namespace Version2._0
{
    public class Question
    {
        public int que_id { get; set; }
        public string que_text { get; set; }

        private bool isSelected;
        public bool IsSelected
        {
            get { return isSelected; }
            set
            {
                isSelected = value;
                 // SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, item.que_id, ans);
                // how can I get the surveyId and emp[empIndex].Id here
            }
        }
    }
}

【问题讨论】:

  • 您根本不应该使用 Click 事件处理程序。相反,将其中一个 RadioButtons 的 IsChecked 属性绑定到 Question 类中的布尔属性。然后对视图模型中该属性的更改做出反应。
  • 哦!我有一个``` public Boolean IsSelected { get;放; }``` 在我的 Question 类中,我如何在这里使用单选按钮?
  • 哦,对不起!你的意思是这样 - `public Boolean IsSelected { get { return IsSelected; } set { // 我的代码放在这里 } } `
  • 除了return IsSelected 将是return isSelected,即使用属性的支持字段。否则你会得到一个 StackOverflowException。
  • 查看我在您的问题中所做的编辑。作为说明,我认为您根本不需要设置或绑定 GroupName。

标签: c# wpf listview radio-button


【解决方案1】:

这就是我解决它的方法,感谢@Clemens(非常感谢!) 我的问题课 -

public class Question
{
    public int que_id { get; set; }
    public string que_text { get; set; }
    public Boolean IsSelected { get; set; }
 }

我的 XAML 部分:

<ListView.ItemTemplate>
            <DataTemplate>
                <DockPanel>
                    <TextBlock DockPanel.Dock="Top" x:Name="quebox" Text="{Binding que_text}"
             Style="{StaticResource ResourceKey=textblock_style }" />
                    <RadioButton  IsChecked="{Binding IsSelected}" x:Name="yesradiobtn" DockPanel.Dock="Left">yes</RadioButton>
                    <RadioButton   x:Name="noradiobtn" DockPanel.Dock="Right">no</RadioButton>
                </DockPanel>
            </DataTemplate>
        </ListView.ItemTemplate>

在选择所有这样的答案后,我将通过单击按钮插入数据库-

private void Button_Click(object sender, RoutedEventArgs e)
    {
        List<Question> items = (List<Question>)listviewQue.ItemsSource;
        int count = 0;
        int totalcnt = items.Count;
        foreach (Question item in items)
        {
            if (item.IsSelectedRadioBtn)
            {
                count++;
                string ans = "yes";
                string res = SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, item.que_id, ans);
                if (!(res == SQLiteDataAccess.SUCCESS))
                {
                    MessageBox.Show("SQLite Exception for 'yes' radiobutton click " + res);
                }
            }
            else
            {
                count++;
                string ans = "no";
                string res = SQLiteDataAccess.AddResponse(surveryId, emp[empIndex].Id, item.que_id, ans);
                if (!(res == SQLiteDataAccess.SUCCESS))
                {
                    MessageBox.Show("SQLite Exception for 'no' button click " + res);
                }
            }
        }
        if (count != totalcnt)
        {
            MessageBox.Show("Please enter the response for all the questions");
        }
        else
        {
            MessageBox.Show("Response recorded successfully");
        }

    }

【讨论】:

  • 请注意,您现在不需要 IsSelectedRadioBtn 属性的支持字段。只需恢复为 public bool IsSelectedRadioBtn { get; set; } 之类的自动属性即可。为什么现在有两个布尔属性IsSelectedIsSelectedRadioBtn?这似乎没有意义。还要注意boolBoolean 是相同的类型。您通常只使用 bool 关键字。
  • 哦,我忘记了我创建的那个临时布尔变量!我现在删除了它:) 非常感谢!
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 2016-06-17
  • 2014-08-27
  • 2015-08-24
  • 1970-01-01
  • 2018-09-19
相关资源
最近更新 更多