views:

539

answers:

4

Hi!

Anyone knows how to return a value from Dispatcher.Invoke in WPF? I want to return the selected index for a combobox.

Thanks!

+1  A: 
int result = -1;

// this is synchronous
myCombo.Invoke(() => 
{
  result = myCombo.SelectedIndex;
});

return result;

This is, of course, kind of clunky. Better design would be to bind the selected index property of your combo box to a Dependency Property of a ViewModel.

Will
A: 

You can't do this directly but you can do this.

Dispatcher.Invoke() actually returns the return value from the delegate you call, so alter your delegate accordingly.

Return Value

Type: System.Object The return value from the delegate being invoked or null if the delegate has no return value.

Source

Chris
Above I post my snippet code, how could I modify this to allow delegate returns selected value for combobox? thanks
toni
Action does not allow a return value, in this case you will have to use a solution like @Will
Chris
Will solution doesn't work in ComboBox WPF Control. I get an error.
toni
@toni and the error is....?
Will
+1  A: 

This is my method to retrieve selected value for a combobox, how can I say delegate to return value?

    private object getValueCB(System.Windows.Controls.ComboBox cb)
    {
        object obj;


            if (!cb.Dispatcher.CheckAccess())
            {
                obj = cb.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate()
                    {
                        obj = cb.SelectedValue;
                    }
                ));

                return obj;
            }
            else
            {
                return obj = cb.SelectedValue;
            }

    }
toni
A: 

Hi! I have solved this. The solution is create a custom delegate that returns the desired type like this:

    private object GetValueCB(System.Windows.Controls.ComboBox cb)
    {
        object obj = null;


            if (!cb.Dispatcher.CheckAccess())
            {
                obj = cb.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  (MyDelegate)
                    delegate()
                    {
                        return (obj = cb.SelectedValue);
                    }
                );

                return obj;
            }
            else
            {
                return obj = cb.SelectedValue;
            }

    }

    public delegate object MyDelegate();
toni