What is the proper way to work with the IsSelected property for strings in a dockpane listbox?

764
1
06-07-2019 10:15 AM
JohnPhillipsGeo
New Contributor III

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.

Listbox Dockpane Example

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; }

}

1 Reply
GKmieliauskas
Esri Regular Contributor

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:

https://stackoverflow.com/questions/13611113/how-to-bind-listboxitem-isselected-to-boolean-data-prop...

0 Kudos