WPF MVVM Radio buttons on ItemsControl

前端 未结 4 732
予麋鹿
予麋鹿 2020-12-08 11:08

I\'ve bound enums to radio buttons before, and I generally understand how it works. I used the alternate implementation from this question: How to bind RadioButtons to an e

4条回答
  •  温柔的废话
    2020-12-08 11:35

    Now that I know about x:Shared (thanks to your other question), I renounce my previous answer and say that a MultiBinding is the way to go after all.

    The XAML:

    
        
    
        
            
                
            
            
                
                    
                        
                            
                                
                                
                            
                        
                        
                    
                
            
        
    
    

    The viewmodel:

    class Viewmodel : INPC
    {
        public Viewmodel()
        {
            Choices = new List() { "one", "two", "three" };
            SelectedChoice = Choices[0];
        }
    
        public List Choices { get; set; }
    
        string selectedChoice;
        public string SelectedChoice
        {
            get { return selectedChoice; }
            set
            {
                if (selectedChoice != value)
                {
                    selectedChoice = value;
                    OnPropertyChanged("SelectedChoice");
                }
            }
        }
    }
    

    The converter:

    public class MyConverter : IMultiValueConverter
    {
        object selectedValue;
        object myValue;
    
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            selectedValue = values[0];
            myValue = values[1];
    
            return selectedValue == myValue;
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((bool)value)
            {
                return new object[] { myValue, Binding.DoNothing };
            }
            else
            {
                return new object[] { Binding.DoNothing, Binding.DoNothing };
            }
    
        }
    }
    

提交回复
热议问题