ReactiveUI icon indicating copy to clipboard operation
ReactiveUI copied to clipboard

Winforms, binding to ListBox.SelectedItem not working

Open angelMachin opened this issue 11 years ago • 3 comments

Hi, I am using ReactiveUI 6.4.0.1

I am trying to bind a property in my ViewModel with the selectedItem event in a ListBox View: this.WhenAnyValue(v => v.ItemsListBox.SelectedItem).BindTo(_vm, vm => vm.SelectedItem); or this.WhenAny(v => v.ItemsListBox.SelectedItem, i => (MyItem)i.Value).BindTo(_vm, v => v.SelectedItem);

The problem is that it only works once. The first time my form is loaded, the SelectedItem.get in the viewmodel is invoked, but if I change the selected item I can't get any notification.

Thanks

angelMachin avatar Apr 30 '15 07:04 angelMachin

I don't think the ListBox implements INPC, so you won't be able to use WhenAny on it like that. If you register an ILogger implementation you will probably see a warning like POCOObservableForProperty: {class} is a POCO type and won't send change notifications, WhenAny will only return a single value! after you attempt the binding.

You should be able to use Observable.FromEvent on the SelectedIndexChanged event of your listbox to get a stream of changes, then use BindTo from there.

rdavisau avatar Apr 30 '15 08:04 rdavisau

It makes sense, I was misled by the fact it was working once. Thanks

angelMachin avatar Apr 30 '15 08:04 angelMachin

In case someone needs it:

       Observable.FromEventPattern(ev => ItemsListBox.SelectedValueChanged += ev, ev => ItemsListBox.SelectedValueChanged -= ev)
            .Select(_ => ItemsListBox.SelectedItem)
            .BindTo(_vm, vm => vm.SelectedItem);

angelMachin avatar Apr 30 '15 11:04 angelMachin