Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

How to use ItemContainerGenerator to select an item in a ListBox

$
0
0

In a MVVM application, I have a Listbox with a designated SelectedValuePath = "ownerID".  After adding a new record to the source data table, I want to regenerate the ListBox for its ItemSource and then select the new item in the ListBox.  It all works well until I get to the point where I try to select the item using a DataRowView and ItemContainerGenerator.  The row is found, and intellisense displays the correct SelectedValue and DisplayMember for the row ItemArray, but the ItemContainerGenerator for some reason returns a null value for the conversion to a ListBoxItem.

XAML for the ListBox:

<ListBox Grid.Row="0" Grid.Column="0"  Margin="17,8,15,26" Name="listBox1"
        Height="Auto"
        ItemsSource="{Binding Tables[0]}"
        DisplayMemberPath="ownerName"
        SelectedValuePath="ownerID" 
        ScrollViewer.VerticalScrollBarVisibility="Auto"
        />

C# to bind the data and to select the ListBoxItem:

DataSet dtSet = new DataSet();
private void bindData(object parameter)
{
    try
    {
        dtSet.Clear();
        string sql = "SELECT ownerID, ownerName FROM owners ORDER BY ownerSort;";
        command = new OleDbCommand(sql, GlobalDB.dbConn);
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = command;
        adapter.Fill(dtSet, "owners");
        mView.listBox1.DataContext = dtSet;
        adapter.Dispose();
    }
    catch (Exception x)
    {
        MessageBox.Show(x.Message);
    }
}
private void displayNewOwner(object obj)
{
    int iNewOwnerID = (int)obj;
    foreach (DataRowView rowView in mView.listBox1.Items)
    {
        if (Convert.ToInt32(rowView.Row["ownerID"]) == iNewOwnerID)
        {
            ListBoxItem li = mView.listBox1.ItemContainerGenerator.ContainerFromItem(rowView) as ListBoxItem;
            li.IsSelected = true;
        }
    }
}

The conversion fails in the displayNewOwner() method.  The value for iNewOwnerID is correct.  The If() block finds the correct rowView.  But "ListBoxItem li" gets a null value even though intellisense  shows that rowView contains the correct SelectedValue and DisplayMember in its ItemArray.  Then, of course, the code throws an exception at "li.IsSelected = true;".

What am I missing here?


Rob E.




Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>