WPF change notification of user control inside item template not working - c#

I'm trying to bind each view model in an ObservableCollection<FilterControlViewmodel> as DataContext to a user control FilterControl in an ItemsControl.
The binding itself works fine. "InitialFilterName" is displayed correctly from FilterControlViewmodel.FilterName but any updates on the property are not notified to the UI.
Also adding elements to ObservableCollection<FilterControlViewmodel> is working find and adding additional user controls. But again the values inside the FilterControlViewmodel are not updated to the UI.
Any hint on where the notification is missing is appreciated. Thanks.
MainWindow.xaml
<Window.DataContext>
<local:MainWindowViewmodel/>
</Window.DataContext>
<Grid>
<ItemsControl ItemsSource="{Binding FilterViewmodel.FilterControls}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<filter:FilterControl DataContext="{Binding}"></filter:FilterControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
FilterControl.xaml
<UserControl.DataContext>
<local:FilterControlViewmodel/>
</UserControl.DataContext>
<Grid>
<Label Grid.Column="0" Grid.Row="0" Content="{Binding FilterName}"></Label>
<ComboBox Grid.Column="0" Grid.Row="1" ItemsSource="{Binding FilterValues}" SelectedItem="{Binding FilterValueSelected}"></ComboBox>
<Button Grid.Column="1" Grid.Row="1" Content="X" Command="{Binding ResetFilterCommand}"></Button>
</Grid>
MainWindowViewmodel.cs
public class MainWindowViewmodel : INotifyPropertyChanged
{
public FilterViewmodel FilterViewmodel
{
get => _filterViewmodel;
set
{
if (Equals(value, _filterViewmodel)) return;
_filterViewmodel = value;
OnPropertyChanged();
}
}
FilterViewmodel.cs
public class FilterViewmodel : INotifyPropertyChanged
{
public ObservableCollection<FilterControlViewmodel> FilterControls
{
get => return _filterControls;
set
{
if (Equals(value, _filterControls)) return;
_filterControls = value;
OnPropertyChanged();
}
}
FilterControlViewmodel.cs
public class FilterControlViewmodel : INotifyPropertyChanged
{
private string _filterName = "InitialFilterName";
public string FilterName
{
get => _filterName;
set
{
if (value == _filterName) return;
_filterName = value;
OnPropertyChanged();
}
}

You should remove the following markup as it creates another instance of FilterControlViewmodel:
<UserControl.DataContext>
<local:FilterControlViewmodel/>
</UserControl.DataContext>
The FilterControl will then inherit its DataContext from the current item (FilterControlViewmodel) in the ItemsControl without you having to set the DataContext property explicitly:
<ItemsControl ItemsSource="{Binding FilterViewmodel.FilterControls}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<filter:FilterControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

Related

TabItem Content IsEnabled binding

I'm creating a WPF application using MVVM pattern (at least I'm trying). There is <TabControl> with bound ItemsSource,which is an ObservableCollection<TabModel> Tabs. Tabs has Name and Items property, where Items is a list of ControlModel, which means Controls. I have problem with binding IsEnabled property to Grid where Items are placed.
Below there is a part of my code presenting the way I'm doing this:
private ObservableCollection<TabModel> tabs;
public ObservableCollection<TabModel> Tabs
{
get
{
if (tabs == null)
{
tabs = new ObservableCollection<TabModel>();
RefreshTabs();
}
return tabs;
}
set
{
tabs = value;
OnPropertyChanged("Tabs");
}
}
\\Tab Model
public string Name { get; set; }
private List<ControlModel> items;
public List<ControlModel> Items
{
get { return items; }
set
{
items = value;
OnPropertyChanged("Items");
}
}
And xaml...
<TabControl Margin="0,100,0,0" ItemsSource="{Binding Tabs,UpdateSourceTrigger=PropertyChanged}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ScrollViewer VerticalScrollBarVisibility="Hidden">
<Grid Margin="5,5,5,5" IsEnabled="{Binding IsProductEditionEnabled}">
<!--<Grid Margin="5,5,5,5">-->
<ItemsControl ItemsSource="{Binding Items,UpdateSourceTrigger=PropertyChanged}" ItemTemplateSelector="{StaticResource ControlTemplateSelector}"/>
</Grid>
</ScrollViewer>
</DataTemplate>
</TabControl.ContentTemplate>
The part...
<Grid Margin="5,5,5,5" IsEnabled="{Binding IsProductEditionEnabled}">
is not working. There is no error. This grid is always disabled. By default it's false.
private bool isProductEditionEnabled = false;
public bool IsProductEditionEnabled
{
get { return isProductEditionEnabled; }
set
{
isProductEditionEnabled = value;
OnPropertyChanged("IsProductEditionEnabled");
}
}
The question is : How to bind IsEnabled in my case properly?
You are inside a DataTemplate so you need to specify where the parent DataContext is when you do the binding, something like this:
<DataTemplate>
<ScrollViewer VerticalScrollBarVisibility="Hidden">
<Grid IsEnabled="{Binding Path=DataContext.IsProductEditionEnabled,
RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}">
</Grid>
</ScrollViewer>
</DataTemplate>

Refresh child DataContext for a tabbed window with MVVM pattern

I am trying to build a WPF window that contains different tabs.
To be more precise the tabs will present different aspect of a given Person (say a short presentation and the list of the books this person has read).
The main window has a combox that allows us to choose the person. I would like the tabs to refresh when the selected person on the combo box is changed.
public interface IPerson
{
string Name { get; }
int Age { get; }
string[] BooksRead { get;}
}
For the sake of simplicity I kept only the two tabs below.
I created my sample following MVVM principles (I use the MVVMLight framework) and I would like my tabs to have their own View controls and ViewModels.
The App.xaml has for ressource the ViewModelLocator
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:WpfApplication1.ViewModel" />
</Application.Resources>
Now the xaml of the mainwindow looks like
<Window.DataContext>
<Binding Path="MainViewModel" Source="{StaticResource Locator}" />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<ComboBox ItemsSource="{Binding AvailablePersons}" IsTextSearchEnabled="True" IsEditable="False" SelectedItem="{Binding SelectedPerson}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</StackPanel>
<TabControl Name="Test" VerticalAlignment="Top" HorizontalAlignment="Stretch" SelectedIndex="{Binding SelectedTabIndex}" Grid.Row="2">
<TabItem Name="HomeTab" Header="Summary">
<views:SummaryTabControl/>
</TabItem>
<TabItem Name="ContactsTab" Header="Books">
<views:BooksTabControl/>
</TabItem>
</TabControl>
</Grid>
Now the view of the SummaryTabControl has the following lines for DataContext
<UserControl.DataContext>
<Binding Path="SummaryTabViewModel" Source="{StaticResource Locator}" />
</UserControl.DataContext>
We have something similar for the other tab BooksTabControl...
Now here is the code of the ViewModelLocator based on the Ninject IoC framework.
public class ViewModelLocator
{
private static readonly IKernel _kernel;
static ViewModelLocator()
{
_kernel = new StandardKernel();
_kernel.Bind<IMainViewModel>().To<MainViewModel>().InSingletonScope();
_kernel.Bind<ISummaryTabViewModel>().To<SummaryTabViewModel>();
_kernel.Bind<IBooksReadTabViewModel>().To<BooksReadTabViewModel>();
_kernel.Bind<IPerson>().ToMethod((ctx) =>
{
var mainViewModelInstance = _kernel.Get<IMainViewModel>();
if (mainViewModelInstance.SelectedPerson == null)
{
throw new InvalidOperationException();
}
return mainViewModelInstance.SelectedPerson;
});
}
public static IMainViewModel MainViewModel { get { return _kernel.Get<IMainViewModel>(); } }
public static ISummaryTabViewModel SummaryTabViewModel { get { return _kernel.Get<ISummaryTabViewModel>(); } }
public static IBooksReadTabViewModel BooksReadTabViewModel { get { return _kernel.Get<IBooksReadTabViewModel>(); } }
}
Actually, the SummaryTabViewModel and BooksReadTabViewModel's constructors depend only on the IPerson (see sample below). That is why I created the dynamic binding of IPerson to the MainViewModel SelectedPerson member.
public class SummaryTabViewModel : ISummaryTabViewModel
{
private readonly IPerson _person;
public SummaryTabViewModel(IPerson person)
{
_person = person;
}
public string Name { get { return _person.Name; } }
public int Age { get { return _person.Age; } }
}
The trick is I would like the tabs DataContext to be reloaded when the SelectedPerson is changed. I tried different approaches, one by sending a message so that the MainWindow's codebehind forces the DataContext of the tabs to be reset, however, the tabs did not reload...
How, in my situation, could I force the tabs control to reload and to reask the ViewModelLocator for an 'updated' DataContext ?
The complete sample code can be found in this repository
i dont know the locator stuff, but a simple solution is the following: remove the DataContext stuff from your usercontrol
<UserControl.DataContext>
<Binding Path="SummaryTabViewModel" Source="{StaticResource Locator}" />
</UserControl.DataContext>
EDIT: in addition to your comment. when you wanna change something because SelectedItem changed then why not do this in your MainViewModel?
public IPerson SelectedPerson
{
get {...}
set
{
this._selectedPerson=value;
this.MySummary = SummaryTabViewModel(_selectedPerson);
OnPropertyChanged("SelectedPerson");
}
}
public ISummaryTabViewModel MySummary
{
get {...}
set
{
this._mySummary = value;
OnPropertyChanged("MySummary");
}
}
xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<ComboBox x:Name="cbo" ItemsSource="{Binding AvailablePersons}" IsTextSearchEnabled="True" IsEditable="False" SelectedItem="{Binding SelectedPerson}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</StackPanel>
<TabControl Name="Test" VerticalAlignment="Top" HorizontalAlignment="Stretch" SelectedIndex="{Binding SelectedTabIndex}" Grid.Row="2">
<TabItem Name="HomeTab" Header="Summary">
<views:SummaryTabControl DataContext="{Binding Path=MySummary}"/>
</TabItem>
<TabItem Name="ContactsTab" Header="Books">
<views:BooksTabControl/>
</TabItem>
</TabControl>
</Grid>

How do I bind to a property of an object under a collection of collections?

I have an ObservableCollection of a class (TopLevel) that contains a name property and a list of another ObservableCollection of class (BottomLevel) that has just a name property. The binding on the highest list works, but when I try to bind to the property on the BottomList I get nothing. What am I missing here?
XAML:
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="myGrid" DataContext="topList">
<Border BorderBrush="AliceBlue" Grid.Column="0" BorderThickness="5">
<ItemsControl x:Name="ic1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=TopName}"/>
<Border BorderBrush="AntiqueWhite" Grid.Column="1" BorderThickness="5">
<Button Content="{Binding Path=BottomList.BottomName}"/>
</Border>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</Grid>
Code behind:
public partial class MainWindow : Window
{
public ObservableCollection<TopLevel> topList;
public MainWindow()
{
InitializeComponent();
topList = new ObservableCollection<TopLevel>();
topList.Add(new TopLevel("T" + (1 + topList.Count).ToString()));
topList[0].AddBottom();
topList.Add(new TopLevel("T" + (1 + topList.Count).ToString()));
topList[1].AddBottom();
ic1.ItemsSource = topList;
}
}
public class TopLevel
{
private ObservableCollection<BottomLevel> bottomList;
private string topName;
public void AddBottom()
{
bottomList.Add(new BottomLevel("B" + (1 + bottomList.Count).ToString()));
}
public TopLevel(string x)
{
bottomList = new ObservableCollection<BottomLevel>();
topName = x;
}
public string TopName
{
get
{
return topName;
}
set
{
if (topName!=value)
{
topName = value;
}
}
}
public ObservableCollection<BottomLevel> BottomList
{
get
{
return bottomList;
}
set
{
if (bottomList!=value)
{
bottomList = value;
}
}
}
}
public class BottomLevel
{
private string bottomName;
public BottomLevel(string x)
{
bottomName = x;
}
public string BottomName
{
get
{
return bottomName;
}
set
{
if (bottomName!=value)
{
bottomName = value;
}
}
}
}
Your path for the button is incorrect. BottomList does not have a "Name" property, so you can't bind to it. Instead, just use BottomName as your path.
Since your topList has a collection of "BottomLevel" you'll need some sort of nested items control to iterate over the "bottomList" collection (then use "BottomName" for your path as above).
As it stands, you basically have:
<ItemsControl //List of TopLevel>
//Your data context is now the TopLevel item itself
<Button Path=/> //What goes here? you have a whole collection of BottomLevel items to choose from!
</ItemsControl>
If you have only one item in BottomList Then you can use the below code for Button
<Button Content="{Binding Path=BottomList[0].BottomName}" Height="50"/>
If you want to Bind the BottomList to some List Control you can bind to the DataGrid then you can use the below code.
<Grid x:Name="myGrid" DataContext="topList">
<Border BorderBrush="AliceBlue" Grid.Column="0" BorderThickness="5">
<ItemsControl x:Name="ic1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=TopName}"/>
<Border BorderBrush="AntiqueWhite" Grid.Column="1" BorderThickness="5">
<DataGrid ItemsSource="{Binding Path=BottomList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Path=BottomName}" Height="50"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Border>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</Grid>
Please let me know if you need any more help.

Binding SelectedItem in nested ListBox using Caliburn.Micro

I'm trying to use Caliburn.Micro to bind a view model of a nested ListBox but I'm stuck.
I have a list workspace that is divided in two sections a list of groups containtaining items in a different part of that workspace I want to show the details of either a group or an item in a group depending on what is the SelectedItem. I'm new to Caliburn.Micro and looked at the documentation and samples but don't know how to connect the dots. Specifically I'm trying to model this after the Caliburn.Micro.HelloScreens sample. The code I have so far:
The ViewModel:
public class AnalyzerGroupWorkspaceViewModel : Conductor<AnalyzerGroupWorkspaceViewModel>, IWorkspace
{
private Selected selected = Selected.AnalyzerGroup;
private const string name = "Analyzers";
public AnalyzerGroupWorkspaceViewModel(
IMappingEngine fromMapper,
IRepository<Model.AnalyzerGroup> analyzerGroups)
{
AnalyzerGroups = new ObservableCollection<IAnalyzerGroupViewModel>(analyzerGroups.GetAll().Select(fromMapper.Map<Model.AnalyzerGroup,AnalyzerGroupViewModel>));
}
public ObservableCollection<IAnalyzerGroupViewModel> AnalyzerGroups { get; private set; }
public string Name { get { return name; } }
public Selected Selected
{
get { return selected; }
set
{
if (value == selected) return;
selected = value;
NotifyOfPropertyChange(() => Selected);
}
}
private IConductor Conductor { get { return (IConductor) Parent; } }
public void Show()
{
var haveActive = Parent as IHaveActiveItem;
if (haveActive != null && haveActive.ActiveItem == this)
{
DisplayName = name;
Selected = Selected.AnalyzerGroup;
}
else
{
Conductor.ActivateItem(this);
}
}
}
The view:
<UserControl x:Class="Philips.HHDx.SSW.AnalyzerGroup.AnalyzerGroupWorkspaceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<DockPanel>
<GroupBox Header="AnalyzerGroups" DockPanel.Dock="Top">
<ListBox x:Name="AnalyzerGroups">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" />
<ListBox x:Name="Analyzers">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Id }"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</GroupBox>
<GroupBox Header="Details">
<ContentControl cal:View.Context="{Binding Selected, Mode=TwoWay}"
cal:View.Model="{Binding}"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Stretch"/>
</GroupBox>
</DockPanel>
</UserControl>
Next to that I have two UserControls that display the detailsof a group or item.
My specific question is how can I use the SelectedItem property of the two ListBoxes to modify the Selected property to switch between displaying the AnalyzerGroup details and the Analyzer details?
I've found the solution to the above described problem the solution consists of four parts:
Add a IsSelected property (that notifies changes) to both 'child' ViewModels
Bind the IsSelected property of the ListBox.ItemContainerStyle to the IsSelected property of the respective ViewModels
Attach a Caliburn.Micro Message to the 'outer' ListBox and use the $eventArgs argument
In the ViewModel bound to the entire UserControl implement the method corresponding to the Message and use the AddedItems property of the eventArgs to set the SelectedViewModel property setting the IsSelected property of the previous SelectedViewModel to false
The code then becomes:
The ViewModel:
public class AnalyzerGroupWorkspaceViewModel : PropertyChangedBase, IAnalyzerGroupWorkspaceViewModel
{
private IAnalyzerViewModel selectedViewModel;
private const string WorkspaceName = "Analyzers";
public AnalyzerGroupWorkspaceViewModel(
IMappingEngine fromMapper,
IRepository<Model.AnalyzerGroup> analyzerGroups)
{
AnalyzerGroups = new ObservableCollection<IAnalyzerGroupViewModel>(
analyzerGroups.GetAll().Select(
fromMapper.Map<Model.AnalyzerGroup, AnalyzerGroupViewModel>));
}
public void SelectionChanged(object eventArgs)
{
var typedEventArgs = eventArgs as SelectionChangedEventArgs;
if (typedEventArgs != null)
{
if (typedEventArgs.AddedItems.Count > 0)
{
var item = typedEventArgs.AddedItems[0];
var itemAsGroup = item as IAnalyzerViewModel;
if (itemAsGroup != null)
{
SelectedViewModel = itemAsGroup;
}
}
}
}
public ObservableCollection<IAnalyzerGroupViewModel> AnalyzerGroups { get; private set; }
public string Name { get { return WorkspaceName; } }
public IAnalyzerViewModel SelectedViewModel
{
get { return selectedViewModel; }
set
{
if (Equals(value, selectedViewModel))
{
return;
}
if (SelectedViewModel != null)
{
SelectedViewModel.IsSelected = false;
}
selectedViewModel = value;
NotifyOfPropertyChange(() => SelectedViewModel);
}
}
}
The View:
<UserControl x:Class="Philips.HHDx.SSW.AnalyzerGroup.AnalyzerGroupWorkspaceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<DockPanel>
<GroupBox Header="AnalyzerGroups" DockPanel.Dock="Top">
<ListBox SelectionMode="Single"
x:Name="AnalyzerGroups"
cal:Message.Attach="[Event SelectionChanged] = [Action SelectionChanged($eventArgs)]">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="2" BorderBrush="DarkGray">
<StackPanel Orientation="Vertical" Margin="10">
<TextBlock Text="{Binding Name}" />
<ListBox SelectionMode="Single" ItemsSource="{Binding Analyzers}" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="DarkGray">
<StackPanel>
<TextBlock Text="{Binding Name }" Margin="10" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</GroupBox>
<GroupBox Header="Details">
<ContentControl cal:View.Model="{Binding SelectedViewModel}" />
</GroupBox>
</DockPanel>
</UserControl>
The answer to your specific question is yes, you can.
On the ViewModel of your UserControl. You create a property that is a ViewModel of either of the two details.
public interface IAnalyzerViewModel
{
}
Next, create two ViewModels for the Views of your Analyzer and AnalyzerGroup views.
public class AnalyzerGroupViewModel : IAnalyzerViewModel
{
}
public class AnalyzerViewModel : IAnalyzerViewModel
{
}
Next, create a property in your UserControl's ViewModel that implements INPC or PropertyChangedBase of Caliburn Micro.
public class MainViewModel :
{
private IAnalyzerViewModel _analyzerViewModel;
public IAnalyzerViewModel SelectedViewModel { get { return _analyzerViewModel; } set { _analyzerViewModel = value; OnPropertyChanged(() => SelectedViewModel); }
//Hook up the selected item changed event of your listbox and set the appropriate ViewModel to show, so if you either want to show the AnalyzerGroup or AnalyzerView.
}
And lastly, just update your MainView to
<ContentControl x:Name="SelectedViewModel"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Stretch"/>
Caliburn will hook up the appropriate bindings and stuff and will pull the View for the associated ViewModel, and also the Name convention part will automatically map it to any public property of its datacontext as long as the names match.

How do I bind a TabControl to a collection of ViewModels?

Basically I have in my MainViewModel.cs:
ObservableCollection<TabItem> MyTabs { get; private set; }
However, I need to somehow be able to not only create the tabs, but have the tabs content be loaded and linked to their appropriate viewmodels while maintaining MVVM.
Basically, how can I get a usercontrol to be loaded as the content of a tabitem AND have that usercontrol wired up to an appropriate viewmodel. The part that makes this difficult is the ViewModel is not supposed to construct the actual view items, right? Or can it?
Basically, would this be MVVM appropriate:
UserControl address = new AddressControl();
NotificationObject vm = new AddressViewModel();
address.DataContext = vm;
MyTabs[0] = new TabItem()
{
Content = address;
}
I only ask because well, i'm constructing a View (AddressControl) from within a ViewModel, which to me sounds like a MVVM no-no.
This isn't MVVM. You should not be creating UI elements in your view model.
You should be binding the ItemsSource of the Tab to your ObservableCollection, and that should hold models with information about the tabs that should be created.
Here are the VM and the model which represents a tab page:
public sealed class ViewModel
{
public ObservableCollection<TabItem> Tabs {get;set;}
public ViewModel()
{
Tabs = new ObservableCollection<TabItem>();
Tabs.Add(new TabItem { Header = "One", Content = "One's content" });
Tabs.Add(new TabItem { Header = "Two", Content = "Two's content" });
}
}
public sealed class TabItem
{
public string Header { get; set; }
public string Content { get; set; }
}
And here is how the bindings look in the window:
<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ViewModel
xmlns="clr-namespace:WpfApplication12" />
</Window.DataContext>
<TabControl
ItemsSource="{Binding Tabs}">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock
Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<TextBlock
Text="{Binding Content}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Window>
(Note, if you want different stuff in different tabs, use DataTemplates. Either each tab's view model should be its own class, or create a custom DataTemplateSelector to pick the correct template.)
A UserControl inside the data template:
<TabControl
ItemsSource="{Binding Tabs}">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock
Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<MyUserControl xmlns="clr-namespace:WpfApplication12" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
In Prism you usually make the tab control a region so that you don't have to take control over the bound tab page collection.
<TabControl
x:Name="MainRegionHost"
Regions:RegionManager.RegionName="MainRegion"
/>
Now the views can be added via registering itself into the region MainRegion:
RegionManager.RegisterViewWithRegion( "MainRegion",
( ) => Container.Resolve<IMyViewModel>( ).View );
And here you can see a speciality of Prism. The View is instanciated by the ViewModel. In my case I resolve the ViewModel throught a Inversion of Control container (e.g. Unity or MEF). The ViewModel gets the View injected via constructor injection and sets itself as the View's data context.
The alternative is to register the view's type into the region controller:
RegionManager.RegisterViewWithRegion( "MainRegion", typeof( MyView ) );
Using this approach allows you to create the views later during runtime, e.g. by a controller:
IRegion region = this._regionManager.Regions["MainRegion"];
object mainView = region.GetView( MainViewName );
if ( mainView == null )
{
var view = _container.ResolveSessionRelatedView<MainView>( );
region.Add( view, MainViewName );
}
Because you have registered the View's type, the view is placed into the correct region.
I have a Converter to decouple the UI and ViewModel,thats the point below:
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Tab,Converter={StaticResource TabItemConverter}"/>
</DataTemplate>
</TabControl.ContentTemplate>
The Tab is a enum in my TabItemViewModel and the TabItemConverter convert it to the real UI.
In the TabItemConverter,just get the value and Return a usercontrol you need.
My solution uses ViewModels directly, so I think it might be useful to someone:
First, I bind the Views to the ViewModels in the App.xaml file:
<Application.Resources>
<DataTemplate DataType="{x:Type local:ViewModel1}">
<local:View1/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}">
<local:View2/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel3}">
<local:View3/>
</DataTemplate>
</Application.Resources>
The MainViewModel looks like this:
public class MainViewModel : ObservableObject
{
private ObservableCollection<ViewModelBase> _viewModels = new ObservableCollection<ViewModelBase>();
public ObservableCollection<ViewModelBase> ViewModels
{
get { return _viewModels; }
set
{
_viewModels = value;
OnPropertyChanged();
}
}
private ViewModelBase _currentViewModel;
public ViewModelBase CurrentViewModel
{
get { return _currentViewModel; }
set
{
_currentViewModel = value;
OnPropertyChanged();
}
}
private ICommand _closeTabCommand;
public ICommand CloseTabCommand => _closeTabCommand ?? (_closeTabCommand = new RelayCommand(p => closeTab()));
private void closeTab()
{
ViewModels.Remove(CurrentViewModel);
CurrentViewModel = ViewModels.LastOrDefault();
}
private ICommand _openTabCommand;
public ICommand OpenTabCommand => _openTabCommand ?? (_openTabCommand = new RelayCommand(p => openTab(p)));
private void openTab(object selectedItem)
{
Type viewModelType;
switch (selectedItem)
{
case "1":
{
viewModelType = typeof(ViewModel1);
break;
}
case "2":
{
viewModelType = typeof(ViewModel2);
break;
}
default:
throw new Exception("Item " + selectedItem + " not set.");
}
displayVM(viewModelType);
}
private void displayVM(Type viewModelType)
{
if (!_viewModels.Where(vm => vm.GetType() == viewModelType).Any())
{
ViewModels.Add((ViewModelBase)Activator.CreateInstance(viewModelType));
}
CurrentViewModel = ViewModels.Single(vm => vm.GetType() == viewModelType);
}
}
}
MainWindow.XAML:
<Window.DataContext>
<local:MainWindowViewModel x:Name="vm"/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Menu Grid.Row="0">
<MenuItem Header="1" Command="{Binding OpenTabCommand}" CommandParameter="1"/>
<MenuItem Header="2" Command="{Binding OpenTabCommand}" CommandParameter="2"/>
<MenuItem Header="3" Command="{Binding OpenTabCommand}" CommandParameter="3"/>
</Menu>
<TabControl Grid.Row="1" ItemsSource="{Binding ViewModels}" SelectedItem="{Binding CurrentViewModel}">
<TabControl.ItemTemplate>
<DataTemplate DataType="{x:Type MVVMLib:ViewModelBase}">
<TextBlock Text="{Binding Title}">
<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}, Path=DataContext.CloseWindowCommand}">X</Hyperlink>
</TextBlock>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</Grid>
I translated some parts to make it easier to understand, there might be some typos.

Categories