I’m learning ReactiveUI at the moment, and I’m struggling to figure out how to bind a collection to a ListBox in WPF. I already understand the MVVM pattern, and I was able to do this very thing in MVVM Light some years ago, but ReactiveUI is proving more difficult. I haven’t been able to find too many simple examples, just convoluted ones that don’t do a great job at demonstrating the basics. Also, a lot of the answers I’ve found on Stack Overflow are very old, so they don’t use the new Dynamic Data libraries that ReactiveUI recommends nowadays.
I’m working in a very simple WPF application while I try to learn the ropes.
I have a simple view called TextBlockView:
<rxui:ReactiveUserControl x:Class="MvvmSandbox.Views.TextBlockView"
x:TypeArguments="vm:TextBlockViewModel"
xmlns:rxui="http://reactiveui.net"
xmlns:vm="clr-namespace:MvvmSandbox.ViewModels"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MvvmSandbox.Views"
mc:Ignorable="d"
d:DesignHeight="250" d:DesignWidth="500">
<TextBlock x:Name="String" HorizontalAlignment="Center" VerticalAlignment="Center" />
</rxui:ReactiveUserControl>
Here’s the code-behind:
using MvvmSandbox.ViewModels;
using ReactiveUI;
using System.Reactive.Disposables;
namespace MvvmSandbox.Views
{
public partial class TextBlockView : ReactiveUserControl<TextBlockViewModel>
{
public TextBlockView()
{
InitializeComponent();
ViewModel = new TextBlockViewModel();
this.WhenActivated(disposable =>
{
this.Bind(ViewModel, vm => vm.String, v => v.String.Text)
.DisposeWith(disposable);
});
}
}
}
And here’s the view model:
using ReactiveUI;
using System.Collections.ObjectModel;
namespace MvvmSandbox.ViewModels
{
public class ListBoxViewModel : ReactiveObject
{
public ObservableCollection<string> Strings => _strings;
private ObservableCollection<string> _strings;
public ListBoxViewModel()
{
_strings = new ObservableCollection<string>()
{
"This is a test of the Emergency Broadcast System.",
"This is only a test."
};
}
}
}
The view does come out with the items, but they’re collapsed to their minimum height and don’t display the strings themselves; you can see the blue bounding box for the first item here.
RobotitoPrime is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.