Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created December 5, 2013 22:54
Show Gist options
  • Save dtchepak/7815508 to your computer and use it in GitHub Desktop.
Save dtchepak/7815508 to your computer and use it in GitHub Desktop.
`_service.Devices` is hooked up to a `ConnectedDevicesChanged` event, and updates with a full list of connected devices. Need to display all connected devices on the UI. (ideally not completely clearing collection, just adding/removing newly connected/disconnected devices, but i'm not doing that at the moment)
<ListView ItemsSource="{Binding Devices}" />
public class MainViewModel : Screen
{
private ConnectionService _service;
public ObservableCollection<DeviceViewModel> Devices { get; private set; }
public MainViewModel()
{
Devices = new ObservableCollection<DeviceViewModel>();
}
protected override void OnActivate()
{
base.OnActivate();
_service = ConnectionService.Start();
_service
.Devices // :: IObservable<IEnumerable<Device>>
.Select(ds => ds.Select(d => new DeviceViewModel(_service, d)))
.LinkTo(Devices); // syncs observable collection every time connected Devices updates
}
}
public static class Extensions
{
public static IDisposable LinkTo<T>(this IObservable<IEnumerable<T>> source, ObservableCollection<T> target)
{
return source
.ObserveOnDispatcher()
.Subscribe(items =>
{
target.Clear();
foreach (var item in items)
{
target.Add(item);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment