WPF MVVM TabControl DataContext is null - wpf

I'am trying to use a TabControl to display several views but I'm confused in correct setting of the DataContext for the views. I found in several discussions that the DataContext (here TemplateViewModel) will be automatically set to the view (here TemplateView), but this dosen't work for me.
MainWindow:
<TabControl Grid.Row="1" ItemsSource="{Binding Tabs}" SelectedIndex="{Binding SelectedTab}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TabName}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type models:TemplateViewModel}">
<views:TemplateView />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
MainWindowViewModel:
private ObservableCollection<ViewModelBase> _tabs;
public ObservableCollection<ViewModelBase> Tabs
{
get { return _tabs; }
set { SetValue(ref _tabs, value, "Tabs"); }
}
public SomeEvent()
{
TemplateViewModel model = new TemplateViewModel();
model.TabName = value;
Tabs.Add(model);
SelectedTab = Tabs.IndexOf(model);
}
On 'SomeEvent', I create a new TemplateViewModel and add it to the tabs collection of type ObservableCollection. The new tab with correct tabname and a TemplateView is displayed on MainView. The problem is, if I try to get the DataContext in TemplateView constructor the context is empty. Any idea?
public TemplateView()
{
InitializeComponent();
TemplateViewModel model = (TemplateViewModel)DataContext;
}

In MainWindow.xaml.cs in constructor add
this.DataContext = new MainWindowViewModel();

Related

Binding not working inside a <ItemsControl.ItemTemplate>

I can not get the binding of a text property for a DataTemplate in MVVM design pattern.
To show the problem I expose below a simplification of my problem, where I bind two different view properties to the same model property (aka AnObject.Text).
My code in MainWindow.xaml is:
...
<Button Grid.Row="0" Content="{Binding ButtonText}" />
...
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel>
<Label Content="aaaaa" />
<TextBlock Text="{Binding ItemText}" />
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
...
My code behind in MainWindow.xaml.cs (which sets the same DataContext for Button and every item in <ItemsControl ItemsSource>):
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
My code in MainWindowViewModel.cs is:
...
public ObservableCollection<object> MyItems => MyConverter.GetCollection(MyData.List);
public string ItemText => "dddd"; // this DOES works
public string ItemText => AnObject.Text; // this does NOT work
...
public string ButtonText => AnObject.Text; // this DOES works (note, same object property!)
...
Any idea why my binding inside the DataTemplate does not work?
Thanks in advance!
There are various things to understand here:
Button control will have the DataContext set to MainWindowViewModel instance. This is the reason why ButtonText variable value is getting reflected in Button control text.
For ItemsControl the DataContext is the the same as for the Button, i.e. the MainWindowViewModel instance.
Each item in the ItemsControl ItemsSource acts as a DataContext for the elements in the ItemTemplate, i.e. the DockPanel and its child elements. This is managed automatically by the framework. So essentially you will need a public property named ItemText in the class which will act as a DataContext for Dockpanel.
In your case the ItemText property is not the part of the objects which are in list.

Binding usercontrols Datacontext in DataTemplate

I have two usercontrols inside of a TabItem. The TabItem has it's own ViewModel, which has a property that the TabItem's child ContentControl's content bound to. This property represents another viewmodel, which will change the view depending on which one it is. Here's an example:
<TabItem DataContext="{Binding Path=MainLayerTabViewModel, Source={StaticResource ViewModelLocator}}" Header="Layers">
<ContentControl Content="{Binding ChildViewModel}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type vm:LayersViewModel}">
<views:LayersTabView DataContext="{Binding ChildViewModel}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UserDrawnLayersViewModel}">
<views:AlternateLayersTabView DataContext="{Binding ChildViewModel}" />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
Here's the view model used as the datacontext for the tabitem:
public class MainLayerTabViewModel : ViewModelBase
{
public object ChildViewModel { get; set; }
public MainLayerTabViewModel()
{
ChildViewModel = (App.Current.Resources["ViewModelLocator"] as ViewModelLocator).LayersViewModel;
}
}
Now, the two types of possible ViewModels for the ChildViewModel are LayersViewModel and UserDrawnLayersViewModel. When I change ChildViewModel to one of those, the view is properly switched via the DataTemplate. But the DataContext isn't actually being set. Nothing is being bound. I tried creating separate properties for each ViewModel in the MainLayerTabViewModel and binding the DataContext of each view to its own property, but that didn't work either.
I haven't verified this, however I can see couple of issue with your code.
View should be
<ContentControl Content="{Binding ChildViewModel}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type vm:LayersViewModel}">
<views:LayersTabView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UserDrawnLayersViewModel}">
<views:AlternateLayersTabView/>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
ViewModel:
public class MainLayerTabViewModel : ViewModelBase
{
public ViewModelBase ChildViewModel { get; set; }
public MainLayerTabViewModel()
{
ChildViewModel = new LayersViewModel();
//or ChildViewModel = new UserDrawnLayersViewModel();
}
}
Hope that helps..

WPF: binding several views to a TabControl's items

In the current project we work on, we have a main window with several views (each with its own viewmodel) that are presented as items in a tab control. E.g: One tab item is an editor, and contains the editor view as follows:
<TabItem Header="Test Editor">
<TestEditor:TestEditorView DataContext="{Binding TestEditorViewModel}"/>
</TabItem>
Another one shows results:
<TabItem Header="Results Viewer">
<ResultViewer:ResultViewer x:Name="resultViewer1" DataContext="{Binding Path=ResultViewModel}" />
</TabItem>
etc.
I'd like to have the TabItems bound to something in the main window's viewmodel, but I can't figure out how to bind the view's name to any property without breaking the MVVM pattern. I'd like to have something like:
<TabControl.ContentTemplate>
<DataTemplate>
<TestEditor:TestEditorView DataContext ="{Binding TabDataContext}"/>
</DataTemplate>
</TabControl.ContentTemplate>
only with some binding instead of having to know at design time what type will be used as content.
Any ideas?
Usually I have the TabControl's Tabs stored in the ViewModel, along with the SelectedIndex, then I use DataTemplates to determine which View to display
View:
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type ResultViewModel}">
<ResultViewer:ResultViewer />
</DataTemplate>
<DataTemplate DataType="{x:Type EditorViewModel}">
<TestEditor:TestEditorView />
</DataTemplate>
</Window.Resources>
<TabControl ItemsSource="{Binding TabCollection}"
SelectedIndex="{Binding SelectedTabIndex}" />
</Window>
ViewModel:
public class MyViewModel : ViewModelBase
{
publicMyViewModel()
{
TabCollection.Add(new ResultsViewModel());
TabCollection.Add(new EditorViewModel());
SelectedTabIndex = 0;
}
private ObservableCollection<ViewModelBase> _tabCollection
= new ObservableCollection<ViewModelBase>();
public ObservableCollection<ViewModelBase> TabCollection
{
get { return _tabCollection };
}
private int _selectedTabIndex;
public int SelectedTabIndex
{
get { return _selectedTabIndex; }
set
{
if (value != _selectedTabIndex)
{
_selectedTabIndex = value;
RaisePropertyChanged("SelectedTabIndex");
}
}
}
}

TabControl fails to create first tab when using data binding

I have a tab control which items source I databind to an observable collection. I use data templates to define the visual representation of the tab's headers and content.
When I add an item to the observable collection I get a tab header but no content. When I add a second item to the observable collection I get tab headers and content for both items. So first when the second item is added to the observable collection, the content for the first tab is created. Anyone knows if this is a bug or can explain why it happens? Is there a workaround? I tried using template selector with same result. Below is sample code to reproduce.
I tested this with both .NET 3.5 and 4.0.
XAML:
<Window x:Class="TabDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Button Content="Add new tabitem" Click="OnAdd" />
<TabControl
ItemsSource="{Binding Path=Items}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</StackPanel>
</Window>
Code behind:
public partial class Window1
{
public Window1()
{
InitializeComponent();
Items = new ObservableCollection<int>();
DataContext = this;
}
public ObservableCollection<int> Items { get; set; }
private void OnAdd(object sender, RoutedEventArgs e)
{
Items.Add(_random.Next(100));
}
private readonly Random _random = new Random();
}
If you set SelectedIndex="0" on your TabControl, it will work around this issue. I believe this has to do with a bug coercing the SelectedIndex as items are added/removed.

How to make ListBox editable when bound to a List<string>?

Edit: The basic problem is binding a List to ListBox(or any other control). So I am editing the question.
I bound a list of string to a ListBox as below. However when I change the contents of the textbox it is not changing the string in the source list.Why?
public partial class MainWindow : Window
{
List<string> _nameList = null;
public List<string> NameList
{
get
{
if (_nameList == null)
{
_nameList = new List<string>();
}
return _nameList;
}
set
{
_nameList = value;
}
}
public MainWindow()
{
NameList.Add("test1");
NameList.Add("test2");
InitializeComponent();
}
And the XAML
<ListBox Grid.Row="0" Grid.Column="0" DataContext="{Binding ElementName=main}" ItemsSource="{Binding NameList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding .,Mode=OneWayToSource , UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The DataContext of each ListBoxItem is the string itself, so the path of your binding is empty (.). TwoWay and OneWayToSource bindings require a path, since you can't just replace the current DataContext. So you need to wrap your string in an object that exposes the string as a property:
public class StringItem
{
public string Value { get; set; }
}
Expose the strings as a list of StringItem:
public partial class MainWindow : Window
{
List<StringItem> _nameList = null;
public List<StringItem> NameList
{
get
{
if (_nameList == null)
{
_nameList = new List<StringItem>();
}
return _nameList;
}
set
{
_nameList = value;
}
}
public MainWindow()
{
NameList.Add(new StringItem { Value = "test1" });
NameList.Add(new StringItem { Value = "test2" });
InitializeComponent();
}
And bind to the Value property:
<ListBox Grid.Row="0" Grid.Column="0" DataContext="{Binding ElementName=main}" ItemsSource="{Binding NameList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Value, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Note that StringItem will also need to implement INotifyPropertyChanged so that bindings are automatically updated. You should also expose the list as an ObservableCollection<T> rather than a List<T>
May be it helsp?
<ListBox Name="lsbList">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Value}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
you can create a DataGridTemplateColumn.CellEditingTemplate with an itemscontrol and textboxes to edit your items
If I didn't misunderstand your question, it is pretty easy to implement. Look:
<ComboBox Text="My Comment 5 with addition." IsEditable="True" Height="25" Width="200">
<ComboBoxItem>My comment1</ComboBoxItem>
<ComboBoxItem>My comment2</ComboBoxItem>
</ComboBox>

Resources