how to bind a boolean to combobox in wpf

前端 未结 4 1998
傲寒
傲寒 2020-12-06 10:26

Well I was wondering how to bind a boolean property to a combobox.Combobox will be a yes/no combobox.

4条回答
  •  独厮守ぢ
    2020-12-06 11:05

    You could use a ValueConverter to convert the boolean value to a ComboBox index and back. Like this:

    public class BoolToIndexConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return ((bool)value == true) ? 0 : 1;   
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return ((int)value == 0) ? true : false;
            }
        }
    }
    

    Assuming Yes is on index 0 and No on index 1. Then you'd have to use that converter in binding to the SelectedIndex property. For this, you declare your converter in your resources section:

      
        
      
    

    Then you use it in your binding:

    
    

提交回复
热议问题