IsSelected property does not work on ComboBoxItem. What is the reason?

WITH#:

ComboBoxItem cbItemTrue = new ComboBoxItem(); cbItemTrue.Content = "Исправлена"; cbItemTrue.Tag = true; ComboBoxItem cbItemFalse = new ComboBoxItem(); cbItemFalse.Content = "Не исправлена"; cbItemFalse.Tag = false; if (obj) cbItemTrue.IsSelected = true; else cbItemFalse.IsSelected = true; return new List<ComboBoxItem>() { cbItemTrue, cbItemFalse}; 

XAML

 <ListView x:Name="listView" Height="145" Width="875" > <ListView.View> <GridView> <GridViewColumn Header="Исправление" > <GridViewColumn.CellTemplate> <DataTemplate> <ComboBox Width="150" ItemsSource="{Binding Corrected, Converter={StaticResource CorrectConverter}}" SelectedIndex="0"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> 
  • and what a method? which calls return new List <ComboBoxItem> () {cbItemTrue, cbItemFalse}; - user2455111
  • 2
    Horror :-) Who uses WPF this way? - user227049
  • 2
    @FoggyFinder hehe I just caught up. what it forms in the ItemSource converter, reminded youtube.com/watch?v=ynlbxcyotoo - user2455111
  • There is one problem. When you set the ItemSource property in the ComboBox , it pulls in the collection and each item is packed .... ATTENTION !!! In ComboBoxItem! :) And you have a collection of type ComboBoxItem . Are you laughing? Your ComboBoxItem generated inside the generated ComboBoxItem . therefore, the IsSelected property IsSelected marked on the generated one. In short, it is not necessary to do. If you decide to commit it, then do it to the end and push your ComboBoxItem collection right into the ComboBox.Items in the code - iRumba

1 answer 1

When the choice is between "Fixed / Not Fixed" use of the CheckBox suggests itself, but if you really want ...

Appearance of the application

Test class such

 public class TestClass { public int Id { get; set; } public string Name { get; set; } public bool IsCorrected { get; set; } public override string ToString() { return $"{Id}-{Name}, Исправлено:{IsCorrected}"; } public static List<TestClass> GetListTestClasses() { List<TestClass> result = new List<TestClass>(); char sign = 'A'; TestClass testClass = null; for (int i = 1; i < 11; i++, sign++) { testClass = new TestClass() { Id = i, Name = sign.ToString() }; if (i % 2 == 0) { testClass.IsCorrected = true; } result.Add(testClass); } return result; } } 

Relationship between MainWindow & MainViewModel

 <Window.DataContext> <local:MainViewModel /> </Window.DataContext> 

Relationship between collection-property, property-selected-element

 <ListView ItemsSource="{Binding FirstList}" SelectedItem="{Binding SelectedElementFirstList}" 

Example of one of the columns

 <ListView.View> <GridView> <GridViewColumn Header="Id" Width="30" DisplayMemberBinding="{Binding Id}"/> 

An example (important!) Column with a ComboBox (note that you use SelectedIndex to select an item)

 <GridViewColumn Header="Исправление" Width="135"> <GridViewColumn.CellTemplate> <DataTemplate> <ComboBox Width="120" ItemsSource="{Binding DataContext.ListStatusIsCorrected, ElementName=window}" SelectedIndex="{Binding IsCorrected, Converter={StaticResource Converter}}"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> 

For the Boolean <-> Int32 conversion operation we use such a converter.

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

The converter is set to connect as a static resource so

 <Window.Resources> <local:BooleanToIntConverter x:Key="Converter"/> </Window.Resources> 

The whole view model looks like this.

 public class MainViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { }; //ctor public MainViewModel() { //заполняем коллекцию тестовыми данными FirstList = new ObservableCollection<TestClass>(TestClass.GetListTestClasses()); } //для показа MessageBox public IMessageService MessageService { get; set; } /// <summary> /// ListView ItemsSource="{Binding FirstList}" /// </summary> private ObservableCollection<TestClass> _FirstList; public ObservableCollection<TestClass> FirstList { get { return _FirstList; } set { _FirstList = value; PropertyChanged(this, new PropertyChangedEventArgs(nameof(FirstList))); } } /// <summary> /// ListView SelectedItem="{Binding SelectedElementFirstList}" /// </summary> private TestClass _SelectedElementFirstList; public TestClass SelectedElementFirstList { get { return _SelectedElementFirstList; } set { _SelectedElementFirstList = value; PropertyChanged(this, new PropertyChangedEventArgs(nameof(SelectedElementFirstList))); } } /// <summary> /// ComboBox ItemsSource="{Binding DataContext.ListStatusIsCorrected, ElementName=window}" /// </summary> public List<string> ListStatusIsCorrected { get; private set; } = new List<string>() { "Не исправлена", "Исправлена" }; /// <summary> /// Кнопка отображения информации об элементе /// </summary> private RelayCommand _ShowInfoAboutTestClassCommand; public RelayCommand ShowInfoAboutTestClassCommand { get { return _ShowInfoAboutTestClassCommand = _ShowInfoAboutTestClassCommand ?? new RelayCommand(OnShowInfoAboutClass); } } private void OnShowInfoAboutClass() { //если элемент не выбран в ListView if (SelectedElementFirstList == null) return; //показываем данные выделенного элемента string message = SelectedElementFirstList.ToString(); MessageService.ShowInfo(message); } }