6

I have WPF listbox:

<ListBox Name="FileDownloads" SelectionMode="Extended">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Name="Url" Text="{Binding Url}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

I like the ability to bind ListBox by name from code behind using: this.OneWayBind(ViewModel, vm => vm.DownloadManager.FileDownloads, v => v.FileDownloads.ItemsSource); Having binding in code-behind helps with refactoring.

Is there any way to bind Url texbox inside the listbox using code-behind?

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Zelid
  • 6,905
  • 11
  • 52
  • 76

1 Answers1

7

Is there any way to bind Url textbox inside the listbox using code-behind?

Not at the moment. You can either use XAML bindings like you're doing now, or you can put your data templates inside UserControls.

A consolation to this somewhat more cumbersome approach, is that if you register your data template UserControls and implement IViewFor<TViewModel> on them:

Splat.Locator.CurrentMutable.Register(typeof(MyView), typeof(IViewFor<MyViewModel>));

Then, you can write the ListBox simply as:

<ListBox Name="FileDownloads" SelectionMode="Extended" />

This line will automatically wire up a DataTemplate for you:

this.OneWayBind(ViewModel, vm => vm.DownloadManager.FileDownloads, v => v.FileDownloads.ItemsSource);
Ana Betts
  • 73,868
  • 16
  • 141
  • 209
  • Great, Thanks! The only thing I needed to write `Splat.Locator.CurrentMutable.Register(() => new FileDownloadControl(), typeof(IViewFor));` not `Splat.Locator.CurrentMutable.Register(typeof(FileDownloadControl), typeof(IViewFor));` – Zelid Aug 24 '14 at 09:13
  • I also added a 'Delete' button inside UserControlView and binded it to ReactiveCommand in a UserControlViewModel. When I subscribe to Delete command from UserControlViewModel - it works fine. When I subscribe to Delete command from UserControlView - it is not fired. I used `this.BindCommand(ViewModel, vm => vm.Delete, v => v.Delete); ViewModel.Delete.Subscribe(x => MessageBox.Show("Click From View"));` and `Delete = ReactiveCommand.Create(); Delete.Subscribe(x=>MessageBox.Show("Click from ViewModel"));` – Zelid Aug 24 '14 at 09:36