Jul
30
2009

AvalonDock Binding DocumentContent in WPF MVVM

I'm working on a WPF application using the MVVM pattern. I'm using the AvalonDock to achieve a Visual Studio look and feel. We needed to have a Tab collection, very much like the open documents in Visual Studio that have to be added and removed at design time. In order to accomplish this we created an ObservableCollection of DocumentContent and bound the DocumentPane ItemsSource to it. So we have a collection of DocumentContent, and a property for the Selected Item. The code also assumes that you have an Images folder directly under the project in order to add an icon to the dropdown selector at the right end. [CLSCompliant(false)] public ObservableCollection<AvalonDock.DocumentContent> DocumentContents { get; private set; } public AvalonDock.DocumentContent SelectedTab { get; set; } The code below goes in the ViewModel of the Window or controls that has the AvalonDock control. public interface ITabViewModel { Guid ObjectId { get; } } public void AddTabViewModel(ITabViewModel tabViewModel) { //if the viewmodel is already added to the tabs just select it. AvalonDock.DocumentContent existingControl = DocumentContents.SingleOrDefault(x => (Guid)x.Tag == tabViewModel.ObjectId); if (existingControl != null) { existingControl.Focus(); exists = true; return; } System.Windows.Data.Binding binding = new System.Windows.Data.Binding("Title"); AvalonDock.DocumentContent avalonDoc = new AvalonDock.DocumentContent() { Title = binding.ToString() }; avalonDoc.SetBinding(AvalonDock.DocumentContent.TitleProperty, binding); avalonDoc.Tag = tabViewModel.ObjectId; System.Windows.Controls.Image iconImage = new System.Windows.Controls.Image() { Width = 16, Height = 16 }; BitmapImage image = new BitmapImage(new Uri(@"pack://application:,,,/Images/cubes.png")); iconImage.Source = image; avalonDoc.Icon = iconImage; MyUserControl myControl = new MyUserControl(); avalonDoc.DataContext = tabViewModel; avalonDoc.Content = myControl; DocumentContents.Insert(0, avalonDoc); avalonDoc.Focus(); }   And this is the XAML bound to the collection of DocumentContents added to the AvalonDock DockingManager or ResizingPanel. <ad:ResizingPanel Orientation="Vertical"> <ad:DocumentPane ItemsSource="{Binding Path=DocumentContents}" SelectedItem="{Binding SelectedTab}" Background="White" > </ad:DocumentPane> </ad:ResizingPanel>

Month List