2
votes

I have a UserControl, which displays an item currently selected in a ListBox. SelectedItem of the ListBox is bound to the ViewModel property of the UserControl, which implements IViewFor interface. The ViewModel property is bound to DataContext of the control.

When I configure the bindings inside UserControl using code, the bindings are not updated whenever ViewModel is set to null (when no item is selected). If I use XAML instead, bindings become null whenever the context becomes null.

Is there a way to achieve the same behavior using Bind method in view constructor?

Here are the TicketsView.xaml.cs bindings:

// Tickets to TicketsListBox.ItemsSource

this
    .OneWayBind(ViewModel,
        vm => vm.Tickets,
        v => v.TicketsListBox.ItemsSource)
    .AddTo(disposables);

// CurrentTicket to TicketsListBox.SelectedItem

this
    .Bind(ViewModel,
        vm => vm.CurrentTicket,
        v => v.TicketsListBox.SelectedItem)
    .AddTo(disposables);

// CurrentTicket to TicketView.ViewModel

this
    .Bind(ViewModel,
        vm => vm.CurrentTicket,
        v => v.TicketView.ViewModel)
    .AddTo(disposables);

Here are the TicketView.xaml.cs bindings:

this
    .WhenAnyValue(v => v.ViewModel)
    .BindTo(this, v => v.DataContext)
    .AddTo(disposables);

this
    .OneWayBind(ViewModel,
        vm => vm.Author,
        v => v.Label.Content)
    .AddTo(disposables);

Whenever ViewModel is set to null bindings do not update. XAML works as expected:

<UserControl ...>
<Grid>
    <Label x:Name="Label" Content="{Binding Author}" />
</Grid>

Any way to achieve the same using code?

1
how did you solve this problem?Artemious

1 Answers

1
votes

How about this replacing your // CurrentTicket to TicketView.ViewModel

this.ViewModel
.WhenAnyValue (vm => vm.CurrentTicket,  
(vm) => vm == null ? null : vm
).BindTo (this.ViewModel, v => v.TicketView.ViewModel);

It will make your null binding in TicketView.xaml.cs work.