I have a TabControl bound to an ObservableCollection property of view models, TabViewModelsCollection.
When another property gets set from within the view models, DeviceState, I'd like to raise a property changed event and tell my TabControls ItemSource to refresh.
The problem is my ItemSource is an ObservableCollection of ViewModels and when I call RaisePropertyChanged("TabViewModelsCollection"); nothing gets updated.
Furthermore my tab views contain multiple user controls and bindings.
The scenario that is supposed to play out is: A device is located on the network, data is collected, and the tabs of device information should then be updated.
Currently my TabControl only updates when I select a different device then select the device whos information I want to see. Think left panel list of devices, right panel with tabs of device info.
Let me know what part of the code you guys might want to see, my codebase is quite large so it would be hard to post it.
Here is where the TabControl is defined in my view:
<!-- Devist List Controls -->
<Grid DockPanel.Dock="Left" Margin="5,5">
<local:DeviceListView DataContext="{Binding DeviceListViewModel}" Grid.Row="0"/>
</Grid>
<GroupBox Header="Device Information" DockPanel.Dock="Right" Margin="0,0,5,5">
<TabControl IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding DeviceListViewModel.SelectedDevice.TabViewModelsCollection}" SelectedItem="{Binding DeviceListViewModel.SelectedDevice.SelectedTabItemVm}" >
<TabControl.Resources>
<DataTemplate DataType="{x:Type vms:HomeViewModel}">
<local:HomeTab/>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:ConfigurationViewModel}">
<Grid>
<local:ConfigurationFileView Visibility="{Binding Configuration, TargetNullValue=Collapsed, FallbackValue=Visible}"/>
<local:ErrorTab Visibility="{Binding Path= Configuration, TargetNullValue=Visible, FallbackValue=Hidden}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:ExpansionModulesViewModelFactory}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<DockPanel >
<local:ExpansionModulesList Title="Discovered/Enumerated"
DataContext="{Binding DiscoveredModules}"
/>
<GridSplitter Width="5"/>
<local:ExpansionModulesList Title="User Action Required"
DataContext="{Binding FaultyModules}"
/>
</DockPanel>
</StackPanel>
<DockPanel Grid.Row="1">
<StackPanel Orientation="Horizontal" FlowDirection="RightToLeft" Margin="5" IsEnabled="{Binding IsCommandEnabled}">
<Button Content="Cancel" HorizontalAlignment="Right"
Command="{Binding CancelExpansionCommand }"
ToolTip="Revert all local modifications by refreshing data from the controller." />
<Separator Width="10"/>
<Button Content="Apply" HorizontalAlignment="Center"
Command="{Binding ApplyExpansionCommand }"
ToolTip="Apply all changes to the controller." />
<Separator/>
</StackPanel>
</DockPanel>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:LogViewModel}">
<local:LogView />
</DataTemplate>
<DataTemplate DataType="{x:Type vms:SignalStrengthViewModel}">
<local:SignalStrengthView />
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
<Setter Property="Header" Value="{Binding Name}" />
</Style>
</TabControl.ItemContainerStyle>
EDIT: I want to be able to call raised property changed on this and have it refresh all of my tab views..
<TabControl IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding DeviceListViewModel.SelectedDevice.TabViewModelsCollection}" SelectedItem="{Binding DeviceListViewModel.SelectedDevice.SelectedTabItemVm}" >
RaisePropertyChanged("TabViewModelsCollection");
Hi please try the next solution:
VM code redaction
private State _deviceState;
private ObservableCollection<object> _tabViewModelsCollection;
public State DeviceState
{
get { return _deviceState; }
set
{
_deviceState = value;
RaisePropertyChanged("DeviceState");
UpdateTabViewModelsCollection();
}
}
public ObservableCollection<object> TabViewModelsCollection
{
get
{
return _tabViewModelsCollection ??
(_tabViewModelsCollection = new ObservableCollection<object>(GetDeviceData()));
}
}
private void UpdateTabViewModelsCollection()
{
_tabViewModelsCollection = null;
RaisePropertyChanged("TabViewModelsCollection");
}
private List<object> GetDeviceData()
{
//implement here the data collection process
throw new NotImplementedException();
}
Xaml redaction (define the UpdateSourceTrigger)
ItemsSource="{Binding DeviceListViewModel.SelectedDevice.TabViewModelsCollection, UpdateSourceTrigger=PropertyChanged}"
Let me know if it was helpful.
Regards.
Related
I have a working dynamic context-menu but there seems to be an issue with the XAML-formatting. To me, it seems as the first template selected will be used for all the menu items.
I would like to achieve a result where the icons are placed in the normal standard location on the left highlighted column and I could still customize the right-side XAML-content for each menu item separately as defined in their DataTemplate.
Heres the XAML-code snipped, used with ListBox
<ListBox.ContextMenu>
<ContextMenu ItemsSource="{Binding ModelContextMenu}"
ItemTemplateSelector="{StaticResource ContextMenuItemDataTemplateSelector}">
</ContextMenu>
</ListBox.ContextMenu>
And the data templates for different menu items:
<DataTemplate x:Key="ChangeColorMenuItem" DataType="MenuItem">
<DockPanel>
<MenuItem Header="{Binding DisplayName}"
Command="{Binding Command}">
</MenuItem>
<xctk:ColorPicker
SelectedColor="{Binding DataContext.SelectedColor, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:View}}}"
Margin="0,0,0,0" />
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="NormalMenuItem" DataType="MenuItem">
<MenuItem Header="{Binding DisplayName}"
Command="{Binding Command}">
<MenuItem.Icon>
<Image Source="{Binding Icon}"/>
</MenuItem.Icon>
</MenuItem>
</DataTemplate>
and finally the template selector class:
public class ContextMenuItemDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (container is FrameworkElement element && item is ContextMenuCommand commandItem)
{
switch (commandItem.MenuType)
{
case ContextMenuType.Normal:
return
element.FindResource("NormalMenuItem") as DataTemplate;
case ContextMenuType.ChangeColor:
return
element.FindResource("ChangeColorMenuItem") as DataTemplate;
default:
throw new ArgumentOutOfRangeException();
}
}
return null;
}
}
EDIT 1
Each MenuItem content is capsulated in the list which is bind to the ContextMenu. The objects in the collection do contain all the data for each MenuItem, such as icon, display name, and ICommand.
public ObservableCollection<ContextMenuCommand> ModelContextMenu => _selectedModel.Commands;
EDIT 2
The desired (standard) icon location marked with blue crosses on the following image:
The problem seems to be two inner MenuItem because of the data templates in question.
The problem was solved by defining ItemTemplate and a custom ItemContainerStyle in the following way:
DataTemplates
<DataTemplate x:Key="ChangeColorMenuItem" DataType="MenuItem">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding DisplayName}"
Padding="5,0,5,0"/>
<xctk:ColorPicker Grid.Column="1"
SelectedColor="{Binding DataContext.SelectedEntityColor, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:PanelView}}}"
Margin="0,0,0,0" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="NormalMenuItem" DataType="MenuItem">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding DisplayName}" />
</Grid>
</DataTemplate>
ListBox ContextMenu
<ListBox.ContextMenu>
<ContextMenu ItemsSource="{Binding CadModelContextMenu}"
ItemTemplateSelector="{StaticResource PanelContextMenuItemDataTemplateSelector}"
UsesItemContainerTemplate="True">
<ContextMenu.Resources>
<ResourceDictionary>
<Image x:Key="menuIcon" x:Shared="false"
Source="{Binding Path=Icon}" Height="16px" Width="16px"/>
</ResourceDictionary>
</ContextMenu.Resources>
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Icon" Value="{StaticResource menuIcon}"/>
<Setter Property="Command" Value="{Binding Command}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</ListBox.ContextMenu>
The icon with this solution is different for each item. The icon is defined in the property of the underlaying object.
So, I've been working on a legend for our map using a WPF treeview to display the groups and layers.
I've gotten it working and displaying just fine, but when I scroll the treeview with the mousewheel, the control starts flickering and the vertical scrollbar for the tree keeps resizing up and down.
The treeview layout is like this:
Group
Layer
Layer sub items
Layer
Layer sub items
Layer
Layer sub items
Group
Layer
etc...
The Group and Layer nodes are tree view items, but the layer sub items are contained within an items control. The layer sub items are not meant to be expanded/contracted, or selected and thus must remain static under the layer node, thus the items control seemed like a sensible choice.
When I scroll with the mouse wheel all the way to the top or bottom of the tree view, the scrollbar starts flicking and resizing, the last few elements of the items control flickers in and out of view (when it shouldn't be in view at all), and sometimes, the tree view will actually scroll back and forth.
If I remove the items control, everything works as it's supposed to. And when I add it back in, it messes up.
Also, if I grab the scroller thumb with the mouse and drag it, everything works fine. No jumping around.
Here's the resource XAML for the control:
<views:DynamicLegendNodeTemplateSelector x:Key="LegendTemplateSelector">
<views:DynamicLegendNodeTemplateSelector.GroupTemplate>
<HierarchicalDataTemplate DataType="{x:Type legend:IDynamicMapLegendGroup}">
<HierarchicalDataTemplate.ItemsSource>
<MultiBinding Converter="{StaticResource LegendNode}">
<Binding Path="Groups"/>
<Binding Path="LegendLayers"/>
</MultiBinding>
</HierarchicalDataTemplate.ItemsSource>
<Grid>
<StackPanel Orientation="Horizontal">
<CheckBox Focusable="False" IsChecked="{Binding IsVisible}" VerticalAlignment="Center">
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center"/>
</CheckBox>
</StackPanel>
</Grid>
</HierarchicalDataTemplate>
</views:DynamicLegendNodeTemplateSelector.GroupTemplate>
<views:DynamicLegendNodeTemplateSelector.LayerTemplate>
<HierarchicalDataTemplate DataType="{x:Type legend:IDynamicMapLayerLegendItem}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Focusable="False" IsChecked="{Binding IsVisible}" VerticalAlignment="Center">
<TextBlock Text="{Binding LayerCaption}" VerticalAlignment="Center"/>
</CheckBox>
<ItemsControl Grid.Row="1"
Margin="16,0,0,0"
BorderThickness="0"
Background="Transparent"
ItemsSource="{Binding LegendItems, IsAsync=True}"
HorizontalAlignment="Left"
HorizontalContentAlignment="Left"
MouseWheel="ItemControls_MouseWheel"
ScrollViewer.CanContentScroll="False"
MouseUp="ItemsControl_MouseUp">
<ItemsControl.Template>
<ControlTemplate>
<ItemsPresenter/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Width="20" Height="20" Stretch="UniformToFill" Source="{Binding Symbol}"/>
<Label Grid.Column="1" Content="{Binding Label}"/>
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</HierarchicalDataTemplate>
</views:DynamicLegendNodeTemplateSelector.LayerTemplate>
</views:DynamicLegendNodeTemplateSelector>
<Style x:Key="TreeItemStyle" TargetType="TreeViewItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<EventSetter Event="MouseUp" Handler="TreeViewItem_MouseUp"></EventSetter>
</Style>
And here's the treeview:
<TreeView x:Name="LegendHierarchy"
MinWidth="200"
ItemsSource="{Binding LegendItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:DynamicArcGisRuntimeMapLegendView}}}"
ItemContainerStyle="{StaticResource TreeItemStyle}"
ItemTemplateSelector="{StaticResource LegendTemplateSelector}" />
This code is using .NET 4.5 in Visual Studio 2015 if that matters.
Regardless, does anyone know what might be causing the problem?
Thanks
So, it goes to show that an attempt at a good nights sleep is helpful.
Apparently, all I had to do was set
VirtualizingPanel.VirtualizationMode="Recycling"
On the treeview control and it starting working.
Here's the full tree view XAML:
<TreeView x:Name="LegendHierarchy"
MinWidth="200"
ItemsSource="{Binding LegendItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:DynamicArcGisRuntimeMapLegendView}}}"
ItemContainerStyle="{StaticResource TreeItemStyle}"
ItemTemplateSelector="{StaticResource LegendTemplateSelector}" UseLayoutRounding="True" ScrollViewer.CanContentScroll="True" HorizontalContentAlignment="Stretch"
VirtualizingPanel.VirtualizationMode="Recycling"/>
I hope this helps others.
I have a TreeView object bound to a DataSet. Inside of the TreeView.ItemTemplate, I am using a HierarchicalDataTemplate containing the controls that I am rendering.
Does anyone know how to change the Visibility property of a control inside of a HierarchicalDataTemplate? I have tried using the BooleanToVisibilityConverter from the .NET framework, but cannot get the binding to work properly.
The boolean variable in my ViewModel named "moveButtonVisibility" is bound to the Visibility property of the button in my XAML. The BooleanToVisibilityConverter then attempts to convert the corresponding boolean value (true/false) to a Visibility value (visible/hidden). "moveButtonVisibility" is not part of the TreeView's ItemSource.
A stripped down version of my code is shown below. I have removed all of the code in my XAML except for the Button control "MoveHereButton" that I want to change the visibility property on:
VIEWMODEL (C#):
private bool _moveButtonVisibility;
public bool moveButtonVisibility
{
get { return _moveButtonVisibility; }
set
{
_moveButtonVisibility = value;
RaiseChange("moveButtonVisibility");
}
}
VIEW (XAML):
<Page>
<Page.Resources>
<BooleanToVisibilityConverter x:Key="visibilityConverter"/>
</Page.Resources>
<Grid HorizontalAlignment="Center" VerticalAlignment="Top">
<TreeView HorizontalAlignment="Center" x:Name="treeView1" VerticalAlignment="Top" ItemsSource="{Binding Path=rsParentChild}" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
<TreeView.ItemContainerStyle>
<Style>
<Setter Property="TreeViewItem.IsExpanded" Value="True"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=rsParentChild, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<Grid Focusable="False" Margin="5,10,5,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Name="MoveHereButton" Content="Move Here" Visibility="{Binding DataContext.moveButtonVisibility, Converter={StaticResource visibilityConverter}}" Click="MoveHereButton_Click" />
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Page>
The following worked:
<Button Name="MoveHereButton"
Content="Move Here"
Visibility="{Binding DataContext.moveButtonVisibility,
RelativeSource={RelativeSource AncestorType={x:Type Page}},
Converter={StaticResource visibilityConverter}}"
Click="MoveHereButton_Click" />
The key was to add:
RelativeSource={RelativeSource AncestorType={x:Type Page}}
inside of the Visibility binding to force the control to use the DataContext of the Page.
I have the following code that creates a TabControl. Each tab contains a UserControl (code is below) that displays different data (one shows Local tax info and the other show Fed/State tax info).
TabControl
<TabControl
Name="MappingTabs"
Margin="6,7,7,8" Padding="6"
Background="White" >
<TabItem
Name="LocalTaxTab"
Padding="6,1"
Header="Local">
<AdornerDecorator>
<DockPanel>
<Border Margin="7">
<GroupBox
Name="LocalTaxesGroup">
<GroupBox.Header>
<TextBlock
FontWeight="Bold"
Text="Local Taxes">
</TextBlock>
</GroupBox.Header>
<StackPanel Margin="20,8,10,0"
Orientation="Vertical">
<local:TaxCodeMappingHeader />
<!-- Note that a row is 25 high, -->
<ScrollViewer
MaxHeight="250"
>
<ItemsControl
Name="LocalTaxCodeMappingControl"
ItemTemplate="{StaticResource MappingRuleTemplate}"
BorderThickness="0"
AlternationCount="2"
IsTextSearchEnabled="False"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding TaxCodesCollection[0].CodeCollection, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}">
<!-- ItemsSource="{Binding Source={StaticResource sortedCodeCollection}}"> -->
</ItemsControl>
</ScrollViewer>
<local:TaxCodeMappingFooter DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</StackPanel>
</GroupBox>
</Border>
</DockPanel>
</AdornerDecorator>
</TabItem>
<TabItem
Name="FedStateTaxesTab"
Padding="6,1"
Header="Federal\State">
<AdornerDecorator>
<DockPanel>
<Border Margin="7">
<GroupBox
Name="FedStateTaxesGroup">
<GroupBox.Header>
<TextBlock
FontWeight="Bold"
Text="Federal \ State Taxes">
</TextBlock>
</GroupBox.Header>
<StackPanel Margin="20,8,10,0"
Orientation="Vertical">
<local:TaxCodeMappingHeader />
<!-- Note that a row is 25 high, -->
<ScrollViewer
MaxHeight="250"
>
<ItemsControl
Name="FedStateTaxCodeMappingControl"
ItemTemplate="{StaticResource MappingRuleTemplate}"
BorderThickness="0"
AlternationCount="2"
IsTextSearchEnabled="False"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding TaxCodesCollection[1].CodeCollection, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}">
<!-- ItemsSource="{Binding Source={StaticResource sortedCodeCollection}}"> -->
</ItemsControl>
</ScrollViewer>
<local:TaxCodeMappingFooter DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</StackPanel>
</GroupBox>
</Border>
</DockPanel>
</AdornerDecorator>
</TabItem>
</TabControl>
</StackPanel>
UserControl (TaxCodeMappingFooter)
<Button
Name="AddButton"
Grid.Row="0"
Grid.Column="0"
Height="20" Width="20"
Command="{Binding Path=DataContext.AddClickCommand}"
CommandParameter="(want the tab name here)"
Style="{StaticResource ImageButton}"
ToolTip="Add a rule"
local:AttachedImage.Image="{StaticResource AddImageSource}" />
The UserControl (TaxCodeMappingFooter) contains an Add button that I need to wire up via RelayCommand to the VM. I need to somehow tell the VM which tab is calling the Add command so that an item can be added to the correct collection. I thought about sending the TabName and then keying off that to know which tab the user is on.
Is my idea correct or is the a better way to do this and if it is correct how do I get the TabName value to pass it back as a CommandParameter?
If you are going to hard code your UI controls as you have done, then perhaps your simplest option is to define a string DependencyProperty in your TaxCodeMappingFooter control:
public static readonly DependencyProperty TabNameProperty = DependencyProperty.
Register("TabName", typeof(string), typeof(TaxCodeMappingFooter));
public string TabName
{
get { return (string)GetTabName(TabNameProperty); }
set { SetTabName(TabNameProperty, value); }
}
Then you could set it from your TabItems:
<local:TaxCodeMappingFooter TabName="FedStateTaxesTab" DataContext="{Binding
RelativeSource={RelativeSource AncestorType=UserControl}}" />
And Bind to it from inside your control:
<Button Name="AddButton" Command="{Binding Path=DataContext.AddClickCommand}"
CommandParameter="{Binding TabName, RelativeSource={RelativeSource
AncestorType=TaxCodeMappingFooter}}" ... />
As others have said, if you model your view model structure appropriately, this would not be much of an issue.
If you really want to bind against an ancestor element, you can use a RelativeSource of FindAncestor, then specify the AncestorType. Note that you may need to tweak AncestorLevel if you are the descendant of more than one TabItem.
{Binding Path=Name
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type TabItem}}}
(wrapping added for clarity)
I have a small application to help myself learn WPF and MVVM etc. I have been using the example by Josh Smith found here to construct my own application. I have got the application adding TabItems, but the embedded DataGrid which is bound to an ObservableCollection<ResourceViewModel> is not showing any data, see the image below:
The DataGrid is the section surrounded in blue. The UserControl also seems to be showing the in the tab itself for some reason, but that is not the problem I am asking about here. The UserControl contains a DataGrid which is bound as follows
<DataGrid ItemsSource="{Binding Resources}"
dataAccess:DataGridTextSearch.SearchValue="{Binding ElementName=searchBox,
Path=Text, UpdateSourceTrigger=PropertyChanged}"
AlternatingRowBackground="Gainsboro"
AlternationCount="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
...</DataGrid>
The Resources property is defined in the ViewModels namespace as
internal class ResourceDataViewModel : WorkspaceViewModel
{
readonly ResourceDataRepository resourceRepository;
public ObservableCollection<ResourceViewModel> Resources { get; private set; }
...
}
Where the ResourceViewmodel holds the information for each row of the DataGrid. I can confirm that the Resource property is populated. When I use the same model outside of MVVM and populate Resource in the same way it works. Can someone provide me with and idea of why this could be happening?
I have attempted to set the explicit path for the binding
ItemsSource="{Binding Path=(viewModels:Resources)}"
but this also does not work. Thanks for your time.
Edit. To address comments. I set the DataContext in the App.xaml.cs file by
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
// Create the ViewModel to which
// the main window binds.
MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
// When the ViewModel asks to be closed,
// close the window.
EventHandler handler = null;
handler = delegate
{
mainWindowViewModel.RequestClose -= handler;
window.Close();
};
mainWindowViewModel.RequestClose += handler;
// Allow all controls in the window to
// bind to the ViewModel by setting the
// DataContext, which propagates down
// the element tree.
window.DataContext = mainWindowViewModel;
window.Show();
}
The XAML of the MainWindow:
<Window x:Class="ResourceStudio.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModels="clr-namespace:ResourceStudio.ViewModels"
xmlns:views="clr-namespace:ResourceStudio.Views"
Title="MainWindow" Height="629.4" Width="814.4">
<Window.Resources>
<ResourceDictionary Source="MainWindowResources.xaml" />
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="284*"/>
<ColumnDefinition Width="567*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="48"/>
<RowDefinition Height="*"/>
<RowDefinition Height="24"/>
</Grid.RowDefinitions>
<DockPanel KeyboardNavigation.TabNavigation="None"
Background="#FFBEC8D8"
Grid.ColumnSpan="2"
Margin="0,0,0.4,0">
<Menu DockPanel.Dock="Top"
Background="#FFF9F9F9"
BorderBrush="Black"
KeyboardNavigation.TabNavigation="Cycle">
<MenuItem Header="_File">
<MenuItem Header="Load _Resource..."
Height="Auto"
Command="{Binding LoadResourceCommand}"/>
<MenuItem Header="_Add Language..."
Height="Auto"/>
<Separator/>
<MenuItem Header="Close _Workspace"
Height="Auto"
Command="{Binding CloseCommand}"/>
<MenuItem Header="E_xit"
Height="Auto" Command="{Binding CloseCommand}" />
</MenuItem>
<MenuItem Header="_Edit">
</MenuItem>
</Menu>
<ToolBarTray DockPanel.Dock="Top" MaxHeight="24" Background="#FFF9F9F9">
<ToolBar Background="#FFF9F9F9">
<Button ToolBar.OverflowMode="Never">One</Button>
<Button>Two</Button>
<Button>Three</Button>
</ToolBar>
</ToolBarTray>
</DockPanel>
<Grid Grid.Row="1" Grid.ColumnSpan="2" Margin="0,0,0.4,23.6" Grid.RowSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TabControl ItemsSource="{Binding Path=Workspaces}"
Grid.Column="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
TabStripPlacement="Top"
Height="Auto"
Width="Auto">
</TabControl>
</Grid>
<StatusBar Grid.Row="2" Grid.ColumnSpan="2" Margin="0,0.4,0.4,-0.4">
<StatusBarItem DockPanel.Dock="Left" Background="#FF007ACC" Margin="0,2,0,0">
<TextBlock Text="Ready" Margin="5,0,0,0"/>
</StatusBarItem>
</StatusBar>
</Grid>
</Window>
Where the MainWindowResources.xaml is:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModels="clr-namespace:ResourceStudio.ViewModels"
xmlns:views="clr-namespace:ResourceStudio.Views"
>
<!--This template applies a ResourceControl view to an instance of the
ResourceDataViewModel class shown in the main window.-->
<DataTemplate DataType="{x:Type viewModels:ResourceDataViewModel}">
<views:ResourceControl/>
</DataTemplate>
<!--This template explains how to render the 'Workspace'
content area in the main window.-->
<DataTemplate x:Key="WorkspacesTemplate">
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
Margin="4"/>
</DataTemplate>
</ResourceDictionary>
The full code for the ResourceControl.xaml is:
<UserControl x:Class="ResourceStudio.Views.ResourceControl"
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:viewModels="clr-namespace:ResourceStudio.ViewModels"
xmlns:dataAccess="clr-namespace:ResourceStudio.DataAccess"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Name="control">
<DockPanel DataContext="{Binding ElementName=control}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBox Text="M" DockPanel.Dock="Top" Name="searchBox" />
<Grid DockPanel.Dock="Top">
<Border BorderBrush="#FF007ACC" BorderThickness="2" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<DataGrid ItemsSource="{Binding Path=(viewModels:Resources)}"
dataAccess:DataGridTextSearch.SearchValue="{Binding ElementName=searchBox, Path=Text, UpdateSourceTrigger=PropertyChanged}"
AlternatingRowBackground="Gainsboro" AlternationCount="2" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<DataGrid.Resources>
<dataAccess:SearchValueConverter x:Key="searchValueConverter"/>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="dataAccess:DataGridTextSearch.IsTextMatch">
<Setter.Value>
<MultiBinding Converter="{StaticResource searchValueConverter}">
<Binding RelativeSource="{RelativeSource Self}" Path="Content.Text" />
<Binding RelativeSource="{RelativeSource Self}" Path="(dataAccess:DataGridTextSearch.SearchValue)" />
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="dataAccess:DataGridTextSearch.IsTextMatch" Value="True">
<Setter Property="Background" Value="Orange" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#FF007ACC"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
</Border>
</Grid>
</DockPanel>
</UserControl>
The TextBox is bound to the DataGrid. When the user types into that TextBox the DataGrid filters and highlights the cells which contains the required text. This however, is not the problem and this code works, it is just the binding to the DataGrid I am interested in. Thanks again for tour time.
Edit2: According to #dkozl's comments I have removed the DataContext="{Binding ElementName=control}" from the DockPanel declaration, so we now have
<DockPanel HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
...
and in the MainWindowResource.xaml I now have
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModels="clr-namespace:ResourceStudio.ViewModels"
xmlns:views="clr-namespace:ResourceStudio.Views"
>
<!--This template applies a ResourceControl view to an instance of the
ResourceDataViewModel class shown in the main window.-->
<DataTemplate DataType="{x:Type viewModels:ResourceDataViewModel}">
<views:ResourceControl DataContext="{Binding}"/>
</DataTemplate>
<!--This template explains how to render the 'Workspace'
content area in the main window.-->
<DataTemplate x:Key="WorkspacesTemplate">
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}"
Margin="4"/>
</DataTemplate>
</ResourceDictionary>
This has not worked. That is my DataGrid in the ResourceControl is not being populated. Thanks again for your time it is most appreciated...
Your UserControl DockPanel.DataContext is bound to ResourceControl control and not to ResourceDataViewModel class. What you need to do instead is to bind DataContext of ResourceControl in your DataTemplate. To achive that first remove DataContext="{Binding ElementName=control}" from ResourceControl.DockPanel and then bind ResourceControl.DataContext to your object by <views:ResourceControl DataContext={Binding}"/>. Also you need to change DataGrid items binding from ItemsSource="{Binding Path=(viewModels:Resources)}" to ItemsSource="{Binding Path=Resources}".
Not part of the original question but same template applies to tab header and tab content because DataTemplate is type specific and in this case tab header content and tab content is the same thing. To solve the issue remove DataTemplate for viewModels:ResourceDataViewModel type and put this directly into your main TabControl:
<TabControl.ContentTemplate>
<DataTemplate>
<views:ResourceControl DataContext={Binding}"/>
</DataTemplate>
</TabControl.ContentTemplate>