I have a listbox which is on a dockpane. I am able to add a list of strings to populate the listbox. I can get the selected items using the ListBox.SelectedItems method. However, I am having issues setting IsSelected = True.
The issue is that the items I am adding are all strings and therefore do not have an IsSelected property. However, if I try adding the items as ListBoxItems, they do not show up in the listbox.
Can someone please take a look at my code and let me know what I am doing wrong or possibly provide an example of adding ListBoxItems that are strings to a listbox on a dockpane? Thanks so much in advance.
xaml:
<ListBox Name="myListBox" Width="Auto" Height="300" Background="{DynamicResource Esri_BackgroundPressedBrush}" SelectionMode="Multiple" ItemsSource="{Binding Assets, Mode=TwoWay}"> </ListBox>
xaml.cs
public Dockpane1View() { InitializeComponent(); foreach (ListBoxItem item in myListBox.Items) { //if item meets certain condition item.IsSelected = true; }}
ViewModel.cs
protected Dockpane1ViewModel() { //AssetSource is just a list of strings foreach (var asset in AssetSource) { _Assets.Add(asset); }; //If I change the string type of the observable collections to ListBoxItem, nothing shows up in the listbox private ObservableCollection<string> _Assets = new ObservableCollection<string>(); public ObservableCollection<string> Assets { set { SetProperty(ref _Assets, value, () => Assets); //NotifyPropertyChanged(() => Assets); } get { return _Assets; } }
Hi John,
I think the better way is to create new object with two members (string and bool) and make binding in xaml. It is not good way to add code to both classes view and viewmodel. Look at this link: