Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6015437
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T02:50:10+00:00 2026-05-23T02:50:10+00:00

This is a running question that I have updated to hopefully be a little

  • 0

This is a running question that I have updated to hopefully be a little more clear.
In short what I am trying to accomplish is pass a property from a listbox selected item to the viewmodel so that this property can be used within a new query. In the code below the Listbox inherits databinding from the parent object. The listbox contains data templates (user controls) used to render out detailed results.

The issue I am having is that within the user control I have an expander which when clicked calls a command from the ViewModel. From what I can see the Listbox object is loosing it’s data context so in order for the command to be called when the expander is expanded I have to explicitly set the datacontext of the expander. Doing this seems to instantiate a new view model which resets my bound property (SelectedItemsID) to null.

Is there a way to pass the selected item from the view to the viewmodel and prevent the value from being reset to null when a button calls a command from within the templated listbox item?

I realize that both Prism and MVVMLite have workarounds for this but I am not familiar with either framework so I don’t know the level of complexity in cutting either of these into my project.

Can this be accomplished outside of Prism or MVVMLite?

original post follows:

Within my project I have a listbox usercontrol which contains a custom data template.

<ListBox x:Name="ResultListBox"
             HorizontalAlignment="Stretch"
             Background="{x:Null}"
             BorderThickness="0"
             HorizontalContentAlignment="Stretch"
             ItemsSource="{Binding SearchResults[0].Results,
                                   Mode=TwoWay}"
             ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             SelectionChanged="ResultListBox_SelectionChanged">
        <ListBox.ItemTemplate>

            <DataTemplate>
                <dts:TypeTemplateSelector Content="{Binding}" HorizontalContentAlignment="Stretch">
                    <!--  CFS Template  -->
                    <dts:TypeTemplateSelector.CFSTemplate>
                        <DataTemplate>
                                <qr:srchCFS />
                        </DataTemplate>
                    </dts:TypeTemplateSelector.CFSTemplate>

                    <!--  Person Template  -->
                    <dts:TypeTemplateSelector.PersonTemplate>
                        <DataTemplate>
                                <qr:srchPerson /> 
                        </DataTemplate>
                    </dts:TypeTemplateSelector.PersonTemplate>

                   <!-- removed for brevity -->

            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

SelectionChanged calls the following method from the code behind

private void ResultListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (((ListBox)sender).SelectedItem != null)
        _ViewModel.SelectedItemID = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
        this.NotifyPropertyChanged(_ViewModel.SelectedItemID);//binds to VM
    }

Within the ViewModel I have the following property

public string SelectedItemID
    {
        get
        {
            return this._SelectedItemID;
        }
        set
        {
            if (this._SelectedItemID == value) 
                return;
            this._SelectedItemID = value;
        }

    }

the listbox template contains a custom layout with an expander control. The expander control is used to display more details related to the selected item. These details (collection) are created by making a new call to my proxy. To do this with an expander control I used the Expressions InvokeCommandAction

<toolkit:Expander Height="auto"
                          Margin="0,0,-2,0"
                          Foreground="#FFFFC21C"
                          Header="View Details"
                          IsExpanded="False"
                          DataContext="{Binding Source={StaticResource SearchViewModelDataSource}}"
                          Style="{StaticResource DetailExpander}">

            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Expanded">
                    <i:InvokeCommandAction Command="{Binding GetCfsResultCommand}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>

Within the ViewModel the delegate command GetCFSResultCommandExecute which is called is fairly straight forward

private void GetCfsResultCommandExecute(object parameter)
    {
        long IdResult;
        if (long.TryParse(SelectedItemID, out IdResult))
        {
            this.CallForServiceResults = this._DataModel.GetCFSResults(IdResult);}

The issue I am experiencing is when selecting a listbox Item the selectionchanged event fires and the property SelectedItemID is updated with the correct id from the selected item. When I click on the expander the Command is fired but the property SelectedItemID is set to null. I have traced this with Silverlight-Spy and the events are consistent with what you would expect when the expander is clicked the listbox item loses focus, the expander (toggle) gets focus and there is a LeftMouseDownEvent but I cannot see anything happening that explains why the property is being set to null. I added the same code used in the selection changed event to a LostFocus event on the listboxt item and still received the same result.

I’d appreciate any help with understanding why the public property SelectedItemID is being set to null when the expander button which is part of the listbox control is being set to null. And of course I would REALLY appreciate any help in learning how prevent the property from being set to null and retaining the bound ID.

Update
I have attempted to remove the datacontext reference from the Expander as this was suggested to be the issue. From what I have since this is a data template item it “steps” out of the visual tree and looses reference to the datacontext of the control which is inherited from the parent object. If I attempt to set the datacontext in code for the control all bindings to properties are lost.

My next attempt was to set the datacontext for the expander control within the constructor as

private SearchViewModel _ViewModel;
    public srchCFS()
    {
        InitializeComponent();
        this.cfsExpander.DataContext = this._ViewModel;
    }

This approach does not seem to work as InvokeCommandAction is never fired. This command only seems to trigger if data context is set on the expander.

thanks in advance

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T02:50:11+00:00Added an answer on May 23, 2026 at 2:50 am

    While this was a hacky approach I found an intermediate solution to get the listbox item value to the view model. I ended up using the selection changed event and passing the value directly to a public property wihtin my view model. Not the best approach but it resolved the issue short term

    private void ResultListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedItem != null)
                _ViewModel.SelectedItemID = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
                MySelectedValue = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
            this.NotifyPropertyChanged(_ViewModel.SelectedItemID);
        }
    

    For this to fire I did have to also setup a property changed handler within the view to push the change to the VM. You can disregard the MySelectedValue line as it is secondary code I have in place for testing.

    For those intereted the generic property changed handler

            public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this running software that is currently being used by about 400 people.
hopefully a simple question here. I'm running a Wordpress blog that has a bunch
NOTE: This question has been updated to provide more detail and insight than the
UPDATED QUESTION Ok, so I have a file with lines like this: 44:) 2.884E-02
Short Question I have a loop that runs 180,000 times. At the end of
Ok so this question has been bothering me for some time. I'm running a
Please forgive me if this is a silly question. We're running into a problem
I'm running a MapReduce task on Gzipped .arc files. Similar to this question ,
I'm trying to get this running: JAXB interface But I always get the error
When running this XNA application it should display a rotated rectangle that moves from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.