mardi 8 janvier 2019

Get checked items from a listbox

I'm just getting used to MVVM and want to do without the code-behind and define everything in the view-models. the combobox represents several selection options (works). I would like to query the elements that have been checked. Unfortunately I can't access them. The textbox should display all selected elements as concatenated string.

View-Model

class MainViewModel : BaseViewModel
    {
        #region Fields

        private ObservableCollection<EssayTypeViewModel> _essayTypes;
        private EssayTypeViewModel _selectedEssayTypes;

        #endregion


        public ObservableCollection<EssayTypeViewModel> EssayTypes
        {
            get => _essayTypes;
            set
            {
                if (_essayTypes == value) return;
                _essayTypes = value; OnPropertyChanged("EssayTypes");
            }
        }


        public EssayTypeViewModel SelectedEssayTypes
        {
            get => _selectedEssayTypes;
            set { _selectedEssayTypes = value; OnPropertyChanged("SelectedEssayTypes"); }
        }


        public MainViewModel()
        {

            // Load Essay Types
            EssayTypeRepository essayTypeRepository = new EssayTypeRepository();
            var essayTypes = essayTypeRepository.GetEssayTypes();
            var essayTypeViewModels = essayTypes.Select(m => new EssayTypeViewModel()
            {
                Text = m.Text
            });

            EssayTypes = new ObservableCollection<EssayTypeViewModel>(essayTypeViewModels);

        }
    }

XAML

<ListBox x:Name="Listitems" SelectionMode="Multiple" Height="75" Width="200" ItemsSource="{Binding EssayTypes}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Text}" IsChecked="{Binding Checked}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <TextBox Text="{Binding Path=SelectedEssayTypes}" Grid.Column="0" Width="160" Height="25" Margin="0,140,0,0"/>




Aucun commentaire:

Enregistrer un commentaire