Get Selected Radio Button in a Group (WPF)

前端 未结 1 1499
清歌不尽
清歌不尽 2021-02-14 22:56

I have a ItemsControl in my program that contains a list of radio buttons.


        

        
1条回答
  •  梦如初夏
    2021-02-14 23:06

    One solution that comes to mind is to add an IsChecked boolean property to your Insertion entities and bind that to the `IsChecked' property of the Radio button. This way you can check the 'Checked' radio button in View Model.

    Here is a quick and dirty example.

    NB: I ignored the fact that the IsChecked can also be null, you could handle that using bool? if required.

    The simple ViewModel

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    
    namespace WpfRadioButtonListControlTest
    {
      class MainViewModel
      {
        public ObservableCollection Insertions { get; set; }
    
        public MainViewModel()
        {
          Insertions = new ObservableCollection();
          Insertions.Add(new Insertion() { Text = "Item 1" });
          Insertions.Add(new Insertion() { Text = "Item 2", IsChecked=true });
          Insertions.Add(new Insertion() { Text = "Item 3" });
          Insertions.Add(new Insertion() { Text = "Item 4" });
        }
      }
    
      class Insertion
      {
        public string Text { get; set; }
        public bool IsChecked { get; set; }
      }
    }
    

    The XAML - The code behind is not shown since it has no code other than than the generated code.

    
      
        
      
      
        
          
            
              
                
              
            
          
        
      
    
    

    0 讨论(0)
提交回复
热议问题