简体   繁体   中英

Select an item from checkedlistbox using wpf,mvvm

I am new to MVVM, I have a checkedlistbox in a view with the list of titles(have bound the exposed property in ViewModel to this checkedlistbox control)...

Here is my XAML code that populates the ListCheckBox -

<ListBox x:Name="lstCode" ItemsSource="{Binding Code,Mode=TwoWay}"  Grid.Row="1" Style="{StaticResource ListBoxStyle}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox x:Name="chkBox" IsChecked="{Binding IsChecked,Mode=TwoWay}"  Content="{Binding Code_Name}" Margin="0" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This control shows the correct list of items with checkboxes for each item in the listbox...

What should be the code in viewmodel to make it work in two way - while getting the codes from database, it should automatically selected the code from the listcheckedbox and when the user selects one or more codes, the viewmodel should be able to know the items selected...

In general, for TwoWay binding, you will need to implement the INotifyPropertyChanged interface on the ViewModel you want to bind to.

In this case, your ViewModel will have to provide a property that returns a collection that your view can bind to, eg an ObservableCollection .

This ObservableCollection already allows you to add, update, and delete items in that list in a way that automatically communicates the changes between View and ViewModel.

For the rest I suggest to start digging into MVVM depths. To fully take advantage of WPF's capabilities, you will need to understand the basics for yourself. A great starting point is this SO thread: MVVM: Tutorial from start to finish?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM