Josh
Josh

Reputation: 657

ObservableCollection of a list of strings in WPF MVVM

I have a list of strings in an ObservableCollection and I want to bind it to a datagrid, listbox or something that will allow me to add a double click event on an item in the list. If you can't tell, I'm new to WPF!!!

Code:

    private ObservableCollection<string> _searchResults;
    public ObservableCollection<string> SearchResults
    {
        get { return _searchResults; }
        set
        {
            _searchResults = value;
            OnPropertyChanged("SearchResults");
        }
    }

<Grid>
    <DataGrid AutoGenerateColumns="False"
              Name="MyGrid"
              Height="400"
              Width="400"
              ItemsSource="{Binding SearchResults}"
              SelectedItem="{Binding MySelectedItemProperty, UpdateSourceTrigger=PropertyChanged}"/>

</Grid>

As a side note, I am also using Caliburn.Micro

Upvotes: 1

Views: 3054

Answers (1)

Jerry
Jerry

Reputation: 6557

In your View, you would do something like this for your Datagrid:

<DataGrid AutoGenerateColumns="False" Name="MyGrid" 
  ItemsSource="{Binding MyListofStrings}"
  SelectedItem="{Binding MySelectedItemProperty, UpdateSourceTrigger=PropertyChanged}"
              CommandHelper:MouseDoubleClick.Command="{Binding MyEditCommand}">

Then in your view model:

         private ObservableCollection<MyStrings> _MyListofStrings;
        public ObservableCollection<MyStrings> MyListofStrings
        {
            get { return _MyListofStrings; }
            set
            {
                  _MyListofStrings = value;
                OnPropertyChanged("MyListofStrings");       //Used for 2 way binding.
            }
        }

Then populate "MyListofStrings" with your data type.

Upvotes: 2

Related Questions