Determining checked Radiobutton from groupbox in WPF following MVVM

后端 未结 5 1904
有刺的猬
有刺的猬 2021-02-05 13:44

I have a groupbox with some radiobuttons. How do I get to know which one which is checked? I am using WPF and following MVVM.



        
5条回答
  •  耶瑟儿~
    2021-02-05 13:54

    There is another MVVM way to solve this using IsChecked Property

    Here's the XAML

    
    
    
    
     
    
    
    
     
      
     
     
    
    

    Your model will be something like this

     public class RadioButtonQuestion
     {
        public string ChoiceQuestion { get; set; }
        public string answer { get; set; }
        public List ListOfAnswerOptions { get; set; }
     }
    
     public class AnswerOption
     {
        public string individualRadioButtonText { get; set; }
        public bool IsChecked { get; set; }
     }
    

    ViewModel will look something like this (The selection logic)

    RadioButtonQuestion r = new RadioButtonQuestion();
    var selectedElement = rbuttonQuestion.answerOptions.FirstOrDefault(c => c.IsChecked);
    r.answer = selectedElement.individualRadioButtonText;
    

    So if you set the datacontext of the view to this viewmodel. You must be able to get it to work.

    Hope it helps.

提交回复
热议问题