How to set selected area in Listbox - wpf

I need to do something like that:
It's Listbox with custom DataTemplate for elements. (I drew green a whole one element of list.)
Now I have this:
If it's real - how to change my DataTemplate(or Listbox styles) to get first resul? (Somehow to set selected area)
DataTemplate
<DataTemplate x:Key="TrackDataTemplate">
<Grid Margin="0,-5,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding FirstPlatformName}" Grid.Row="0" Grid.Column="0"/>
<Path x:Name="Node"
Margin="10,0" Grid.Row="0" Grid.Column="1"
Data="M3.1999443,36.501999 L47.300057,36.501999 47.292366,36.517475 C43.192585,44.521747 34.86105,50 25.25,50 15.638952,50 7.3074172,44.521747 3.2076359,36.517475 z M25.25,0.5 C38.919049,0.49999976 50,11.580952 50,25.25 50,27.599367 49.672657,29.87228 49.061096,32.025615 L48.919384,32.501999 1.5806161,32.501999 1.438906,32.025615 C0.82734287,29.87228 0.5000003,27.599367 0.5,25.25 0.5000003,11.580952 11.580953,0.49999976 25.25,0.5 z"
Fill="{DynamicResource white75}" Stretch="Fill"
Width="17" Height="17"/>
<Rectangle x:Name="Connection" Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Center" VerticalAlignment="Top"
Fill="{DynamicResource white75}" Height="17" Width="4" Margin="10,2,10,0"/>
<TextBlock Grid.Row="1" Grid.Column="2" TextWrapping="Wrap"
Text="{Binding TsAndChannelNumber}"/>
</Grid>
</DataTemplate>
Listbox
<ListBox Grid.Column="1"
SelectedItem="{Binding SelectedTrackSegment}"
ItemsSource="{Binding SelectedTrack.Segments}"
ItemTemplate="{StaticResource TrackDataTemplate}"
Margin="30,20,30,0"/>

For complete control over the ListBoxItem you probably need to change the Template in ItemContainerStyle.
Heres a little test project to show what I mean.
NB Ive added 2 grids around your textblocks so that the Background Property can be changed using the Triggers.
Xaml
<ListBox x:Name="MyList">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid Margin="0,-5,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid x:Name="PlatformGrid">
<TextBlock Text="{Binding FirstPlatformName}" />
</Grid>
<Path x:Name="Node"
Margin="10,0" Grid.Row="0" Grid.Column="1"
Data="M3.1999443,36.501999 L47.300057,36.501999 47.292366,36.517475 C43.192585,44.521747 34.86105,50 25.25,50 15.638952,50 7.3074172,44.521747 3.2076359,36.517475 z M25.25,0.5 C38.919049,0.49999976 50,11.580952 50,25.25 50,27.599367 49.672657,29.87228 49.061096,32.025615 L48.919384,32.501999 1.5806161,32.501999 1.438906,32.025615 C0.82734287,29.87228 0.5000003,27.599367 0.5,25.25 0.5000003,11.580952 11.580953,0.49999976 25.25,0.5 z"
Fill="Blue" Stretch="Fill"
Width="17" Height="17"/>
<Rectangle x:Name="Connection" Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Center" VerticalAlignment="Top"
Fill="Blue" Height="17" Width="4" Margin="10,2,10,0"/>
<Grid x:Name="TSGrid" Grid.Row="1" Grid.Column="2">
<TextBlock TextWrapping="Wrap" Text="{Binding TsAndChannelNumber}"/>
</Grid>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Selector.IsSelectionActive" Value="True"/>
<Condition Property="IsSelected" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="PlatformGrid" Value="Red"/>
<Setter Property="Background" TargetName="TSGrid" Value="Red"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
MainWindows.cs
public MainWindow()
{
InitializeComponent();
Loaded += (s, args) =>
{
this.DataContext = this;
MyList.ItemsSource = LoadSegments();
};
}
private static List<Segment> LoadSegments()
{
var segments = new List<Segment>
{
new Segment { FirstPlatformName = "FPName01", TsAndChannelNumber = "TSNumber0(ChannelNumber0" },
new Segment { FirstPlatformName = "FPName01", TsAndChannelNumber = "TSNumber0(ChannelNumber1" },
new Segment { FirstPlatformName = "FPName01", TsAndChannelNumber = "TSNumber0(ChannelNumber2" },
new Segment { FirstPlatformName = "FPName01", TsAndChannelNumber = "TSNumber0(ChannelNumber3" },
new Segment { FirstPlatformName = "FPName01", TsAndChannelNumber = "TSNumber0(ChannelNumber4" }
};
return segments;
}
Segment.cs
public class Segment
{
public string FirstPlatformName { get; set; }
public string TsAndChannelNumber { get; set; }
}
You will ideally need to 'Edit a copy' of the ItemContainerStyle template in Blend so you get access to all the standard behaviours and then edit the Trigger IsSelected as above
Hope that helps

But I suggest to use two ListBox and use IsSynchronizedWithCurrentItem property to true. So when you make selection on one, it will select the same item on other automatically. And you can define your own data template for each listbox.

Related

Datagrid, Merge/Combine rows, cells and columns

I'm trying to acomplish exactly what this question is requesting, but unfortunately the code sample that was provided as the answer is gone, and I'm also not using WPF Toolkit, here the question that he did:
I am trying to Merge cells in WPF toolkit datagrid .I am trying to do something as shown in the image below.We can do this in Winforms datagrid.But how to do this using WPF toolkit datagrid ?.Or is there any alternative controls..?
Can we do this using listview or listbox..? Or is there any free
controls available which have this functionality ?
I found several answers that manage to do this with the DataGridView control, but I do not want to use Form objects in a WPF project, is there a way to acomplish this?
Recource
<Window.Resources>
<Color x:Key="customBlue" A="255" R="54" G="95" B="177" />
<SolidColorBrush x:Key="customBlueBrush" Color="{StaticResource customBlue}"></SolidColorBrush>
<SolidColorBrush x:Key="customBlueBrushOpacity" Color="LightGray" Opacity="0.11"></SolidColorBrush>
<Style x:Key="calcyListbox" TargetType="ListBox">
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="35"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Height="30" VerticalAlignment="Top" Background="{StaticResource customBlueBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="Manufacturer" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
<TextBlock Text="Name" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1"></TextBlock>
<TextBlock Text="CPU" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="2"></TextBlock>
<TextBlock Text="RAM" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="3"></TextBlock>
<TextBlock Text="Price" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="4"></TextBlock>
</Grid>
<Border Grid.Row="1" SnapsToDevicePixels="True" Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0">
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
<ItemsPresenter />
</ScrollViewer>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="noStyleToListboxItem" TargetType="ListBoxItem">
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border>
<ContentPresenter></ContentPresenter>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
xaml
<ListBox MaxHeight="300" ItemsSource="{Binding ManufacturerList}" Background="{StaticResource customBlueBrushOpacity}" x:Name="ManufacturerListBox" ScrollViewer.VerticalScrollBarVisibility="Auto" Style="{StaticResource calcyListbox}" ItemContainerStyle="{StaticResource noStyleToListboxItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="4*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Company}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Border BorderThickness="0,0,0,1" BorderBrush="Black" ></Border>
<ListBox Grid.Column="1" BorderThickness="1,0,1,1" Background="{StaticResource customBlueBrushOpacity}" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Models}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border BorderThickness="0,0,1,0" BorderBrush="Black" Margin="-2" Grid.Column="0"></Border>
<Border BorderThickness="0,0,1,0" BorderBrush="Black" Margin="-2" Grid.Column="1"></Border>
<Border BorderThickness="0,0,1,0" BorderBrush="Black" Margin="-2" Grid.Column="2"></Border>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="0"/>
<TextBlock Text="{Binding CPU}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1"/>
<TextBlock Text="{Binding Ram}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="2"/>
<TextBlock Text="{Binding price}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="3"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
c#
InitializeComponent();
List<Manufacturer> ManufacturerList = new List<Manufacturer>();
ManufacturerList.Add(new Manufacturer()
{
Company = "DEll",
Models = new List<Model>(){new Model(){CPU = "T7250", Name = "Inspiron1525", price =234434 , Ram= "2048 MB" },
new Model(){CPU = "T5750", Name = "Studio 1535", price =234443 , Ram= "2048 MB" },
new Model(){CPU = "T5780", Name = "Vastro 1510", price =234434 , Ram= "2048 MB" },}
});
ManufacturerList.Add(new Manufacturer()
{
Company = "Lenovo",
Models = new List<Model>(){new Model(){CPU = "T1230", Name = "l123", price =23546454 , Ram= "1024 MB" },
new Model(){CPU = "T1230", Name = "l1423", price =2346456 , Ram= "1024 MB" },
new Model(){CPU = "T1230", Name = "ldf123", price =2344646 , Ram= "1024 MB" },}
});
ManufacturerListBox.ItemsSource = ManufacturerList;
public class Manufacturer
{
public string Company { get; set; }
public List<Model> Models { get; set; }
}
public class Model
{
public string Name { get; set; }
public string Ram { get; set; }
public double price { get; set; }
public string CPU { get; set; }
}
For a merged cell, bind its Margin and set it to a negative value equal to the sum width/height of the associated merged cells - then the cell will spill across and on top the neighboring cells.
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="{{Binding BorderThickness[5], Mode=OneWay}}"/>
<Setter Property="Margin" Value="{{Binding CellMargins[5], Mode=OneWay}}"/>
<Setter Property="Block.TextAlignment" Value="Center"/>
</Style>
The bindings are indexed because CellMargins is an ObservableCollection of Thickness. The viewmodel is row-level, so each column binds to a different index.
Before this gets downvoted, let me say this can lead to some undesirable visual quirks. Getting this to work perfectly requires a bit of code-behind, such as:
The cell margins' negative values need to be updated whenever a column width changes, so I handled the datagrid's LayoutUpdated event, where I iterated through the columns, measured their current ActualWidths and updated the margins accordingly. I likewise update the BorderThickness to show/hide cell borders as needed. Disabling the selection highlight for cells that are "hidden" is another trick.
Note this means keeping track of what cells (i.e., which row viewmodels and column indices) you want merged separately in code-behind.
This method is complicated and probably not the easiest for every situation, but I found it useful for my purposes. I needed a Datagrid where the user could merge/unmerge cells and create/delete columns, similar to Excel. Furthermore, I wanted to stick with DataGridTextColumns (instead of custom TemplateColums) because of their built-in functionality (recognized keyboard edit commands, copy/paste, etc.)

Grid and ItemsControl.ItemContainerStyle in WIndows Phone

I've got a serious problem and i can't solve it. There is the following code what perfectly works in WPF:
<ItemsControl Grid.Row="1" ItemsSource="{Binding GameFields}" HorizontalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="7" Columns="7" Margin="20" HorizontalAlignment="Center" VerticalAlignment="Center" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Command="{Binding SingleStepCommand}" CommandParameter="{Binding Index}" Visibility="{Binding Visible}" Background="Transparent"
Margin="10" BorderBrush="Transparent" BorderThickness="0">
<Button.Content>
<Image Source="{Binding IconPath}" Stretch="Fill" />
</Button.Content>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{Binding X}" />
<Setter Property="Grid.Column" Value="{Binding Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
And a try to implement in Windows Phone(7.1). But all elements of the itemspaneltemplate grid are on each other, i mean on the same X and Y position. Here's what i've tried:
<ItemsControl x:Name="ContentSource" Grid.Row="1" Margin="12,0,12,0" ItemsSource="{Binding GameFields}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RenderTransform>
<TransformGroup>
<TranslateTransform X="{Binding X}" Y="{Binding Y}" />
</TransformGroup>
</Grid.RenderTransform>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Command="{Binding SingleStepCommand}" CommandParameter="{Binding Index}" Visibility="{Binding Visible}" Grid.Row="{Binding X}"
Grid.Column="{Binding Y}">
<Button.Content>
<Image Source="{Binding IconPath}" Stretch="Fill" />
</Button.Content>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<!--ItemsControl.Resources>
<Style TargetType="ContentPresenter">
<Setter Property="Grid.Row" Value="17" />
<Setter Property="Grid.Column" Value="17" />
</Style>
</ItemsControl.Resources-->
</ItemsControl>
3 different way and none of them works. (Resources, TranslateTransform and Button grid.row binding). Do you have any suggestion what im doing wrong or what should i use?
I have to use MVVM strictly, so there's no code behind. Any advice will get thanks and sorry for my english :)
You have got the right idea - you do need to set the Grid.Row and Grid.Column properties on the ContentPresenter. The easiest way to do this is with your own Attached Properties for each.
Something like this:
public class ItemsGridLayout
{
public static int GetGridRow(DependencyObject obj)
{
return (int)obj.GetValue(GridRowProperty);
}
public static void SetGridRow(DependencyObject obj, int value)
{
obj.SetValue(GridRowProperty, value);
}
// Using a DependencyProperty as the backing store for GridRow. This enables animation, styling, binding, etc...
public static readonly DependencyProperty GridRowProperty =
DependencyProperty.RegisterAttached("GridRow", typeof(int), typeof(FrameworkElement), new PropertyMetadata(0, (s, e) =>
{
var presenter = GetItemsPresenter(s);
if (presenter != null)
{
Grid.SetRow(presenter, GetGridRow(s));
}
}));
public static int GetGridColumn(DependencyObject obj)
{
return (int)obj.GetValue(GridColumnProperty);
}
public static void SetGridColumn(DependencyObject obj, int value)
{
obj.SetValue(GridColumnProperty, value);
}
// Using a DependencyProperty as the backing store for GridColumn. This enables animation, styling, binding, etc...
public static readonly DependencyProperty GridColumnProperty =
DependencyProperty.RegisterAttached("GridColumn", typeof(int), typeof(FrameworkElement), new PropertyMetadata(0, (s, e) =>
{
var presenter = GetItemsPresenter(s);
if (presenter != null)
{
Grid.SetColumn(presenter, GetGridColumn(s));
}
}));
static FrameworkElement GetItemsPresenter(DependencyObject target)
{
while (target != null)
{
if (target is ContentPresenter)
{
return target as FrameworkElement;
}
target = VisualTreeHelper.GetParent(target);
}
return null;
}
}
Then in XAML it's used like this:
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button local:ItemsGridLayout.GridRow="{Binding X}"
local:ItemsGridLayout.GridColumn="{Binding Y}"
I ran into the very same problem today. Learning Silverlight after WPF, I didn't expect that this wouldn't work.
After a few more searches to avoid this kind of workaround, I tried to add a Style resource for the ContentPresenter and it worked like a charm in Silverlight 5.
<ItemsControl ItemsSource="{Binding Source={StaticResource CVM}, Path=PagedItems}">
<ItemsControl.Resources>
<Style TargetType="ContentPresenter">
<Setter Property="Grid.Column" Value="{Binding OffsetX}"/>
<Setter Property="Grid.Row" Value="{Binding OffsetY}"/>
</Style>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
...
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
...
<RowDefinition/>
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

Sharing control instance within a view in WPF

I'm having some issues with the wpf tab control. Not sure the title of the question is right I will refine it accoring to answers.
I want to create a simple panel system. I want to inject ot my "panel viewModel" 2 view model
MainViewModel will be display as the main area
PanelViewModel will be display as a panel on the right hand side of the view
the panelViewModel will be hidden by default and a button will display it on top of the main view model when needed
The view look like this:
<UserControl.Resources>
<DataTemplate x:Key="MainWindowTemplate" DataType="{x:Type UserControl}">
<ContentPresenter Content="{Binding DataContext.MainViewModel, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid Visibility="{Binding IsPanelHidden, Converter={StaticResource bool2VisibilityConverter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentControl Grid.Column="0" ContentTemplate="{StaticResource MainWindowTemplate}" />
<Button Grid.Column="1" Content="{Binding PanelTitle}" Command="{Binding Path=ShowPanelCommand}">
<Button.LayoutTransform>
<RotateTransform Angle="90"/>
</Button.LayoutTransform>
</Button>
</Grid>
<Grid Visibility="{Binding IsPanelHidden, Converter={StaticResource revertBool2VisibilityConverter}}">
<ContentControl ContentTemplate="{StaticResource MainWindowTemplate}" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="0.5*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="2" VerticalAlignment="Stretch" Background="Red" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border HorizontalAlignment="Stretch">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding PanelTitle}" Margin="5,5,0,2" HorizontalAlignment="Left"></TextBlock>
<StackPanel Grid.Column="1" Orientation="Horizontal" Margin="0,0,5,0" HorizontalAlignment="Right" >
<Button Content="Minimze" Command="{Binding HidePanelCommand}"/>
</StackPanel>
</Grid>
</Border>
<ContentPresenter Grid.Row="1" Margin="2" Content="{Binding PanelViewModel}" VerticalAlignment="Top"/>
</Grid>
</Border>
</Grid>
</Grid>
The view model look like that:
public class TestTabViewModel : ObservableObject
{
#region private attributes
#endregion
public TestTabViewModel(string panelName, object panelViewModel, object mainViewModel)
{
IsPanelHidden = true;
PanelTitle = panelName;
PanelViewModel = panelViewModel;
MainViewModel = mainViewModel;
ShowPanelCommand = new DelegateCommand(() =>ManagePanelVisibility(true));
HidePanelCommand = new DelegateCommand(() => ManagePanelVisibility(false));
}
#region properties
public string PanelTitle { get; private set; }
public bool IsPanelHidden { get; private set; }
public object PanelViewModel { get; private set; }
public object MainViewModel { get; private set; }
public DelegateCommand ShowPanelCommand { get; private set; }
public DelegateCommand HidePanelCommand { get; private set; }
#endregion
#region private methods
private void ManagePanelVisibility(bool visible)
{
IsPanelHidden = !visible;
RaisePropertyChanged(() => IsPanelHidden);
}
#endregion
}
So for so good, this system work fine I aslo added some pin command but I remove them from here to make it "simple".
My problem come when the main view model hold a tab control. In this, case if I select a tab and "open" the panel, the tab selected is "changed". In fact it's not changed it's just that I display another contentControl which is not synchronize with the previouse one. I guess that the view instance is not the same even if the viewmodel behind is.
So how do I share a view instance within a view (or have the selection process synchornized)? My first guest was to use the datatemplate (as show in the example) but it did not solve my problem.
By the way, I know some third-party handling panel docking pin ... (eg avalon) but all the one I found are really too much for my simple need.
Thanks for the help
Your best bet would probably be to replace your two Grids with a single ContentControl, and switch the Template on button click or in a Trigger. This way your actual Content (the TabControl) will be the same, but the template used to display the Content will change
Here's a quick example:
<Window.Resources>
<ControlTemplate x:Key="Grid1Template" TargetType="{x:Type ContentControl}">
<DockPanel>
<Grid Background="CornflowerBlue" Width="100" DockPanel.Dock="Left" />
<ContentPresenter Content="{TemplateBinding Content}" />
</DockPanel>
</ControlTemplate>
<ControlTemplate x:Key="Grid2Template" TargetType="{x:Type ContentControl}">
<DockPanel>
<Grid Background="CornflowerBlue" Width="100" DockPanel.Dock="Right" />
<ContentPresenter Content="{TemplateBinding Content}" />
</DockPanel>
</ControlTemplate>
</Window.Resources>
<DockPanel>
<ToggleButton x:Name="btnToggle" Content="Toggle View" DockPanel.Dock="Top" />
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Template" Value="{StaticResource Grid1Template}" />
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=btnToggle, Path=IsChecked}" Value="True">
<Setter Property="Template" Value="{StaticResource Grid2Template}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
<TabControl>
<TabItem Header="Tab1" />
<TabItem Header="Tab2" />
<TabItem Header="Tab3" />
</TabControl>
</ContentControl>
</DockPanel>
i dont know if i get what you want but i think that you could do the following.
i assume that you want some "MainViewmodeldata" be presented as your tabcontrol.
so i woulf first create a datatemplate for this.
<UserControl.Resources>
<DataTemplate DataType="{x:Type MainViewmodeldata}">
<TabControl>
<TabItem Header="Tab1">
<TextBlock Grid.Column="1" Text="Tab1Content"/>
</TabItem>
<TabItem Header="Tab2">
<TextBlock Grid.Column="1" Text="Tab2Content"/>
</TabItem>
</TabControl>
</DataTemplate>
</UserControl.Resources>
now i would just bind my this mainviewmodeldata to the contentcontrol and let wpf render it for you. i really dont know if you still need these two grids, cause i dont know what you wanna achieve.
<Grid x:Name="Grid1" Visibility="{Binding IsPanelHidden, Converter={StaticResource bool2VisibilityConverter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentControl Content="{Binding MainViewmodelData}" />
<StackPanel Grid.Column="1">
<Button x:Name="Button1" Content="Switch look" Command="{Binding ShowPanelCommand}"/>
<TextBlock Text="Look1"/>
</StackPanel>
</Grid>
<Grid x:Name="Grid2" Visibility="{Binding IsPanelHidden, Converter={StaticResource revertBool2VisibilityConverter}}">
<ContentControl Content="{Binding MainViewmodelData}" />
<StackPanel HorizontalAlignment="Right">
<Button x:Name="Button2" Content="Switch look" Command="{Binding HidePanelCommand}"/>
<TextBlock Text="Look2"/>
</StackPanel>
</Grid>
</Grid>

Binding TabItem Header to Textblock in Style?

I'm trying to create a tab control in which the Header on the TabItem is binded in a textbox that is in the controltemplate of the tabcontrol. how can i do this through binding in the style?
Here's my code:
<Style x:Key="TabControlTest1" TargetType="TabControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabControl">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!--Area for TabItems-->
<Border Grid.Column="0"
Grid.Row="0"
>
<TabPanel IsItemsHost="True"
x:Name="HeaderPanel"
Background="Transparent" />
</Border>
<!--Content of SelectedItems-->
<Border Grid.Column="1"
BorderBrush="{DynamicResource TabControlContentPresentBorderBrush}"
BorderThickness="0,1,1,1"
Background="{DynamicResource TabControlContentPresentBackgroundBrush}"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--///This is Where I want to bind the Header///-->
<Label
Grid.Row="0"
Foreground="AliceBlue"
Content="{Binding Header, ElementName=TabItem}"/>
<ContentPresenter
Grid.Row="1"
x:Name="PART_SelectedContentHost"
ContentSource="SelectedContent"
Margin="5"/>
</Grid>
</Border>
<ControlTemplate x:Key="TabItemControlTemplate" TargetType="{x:Type TabItem}">
<!--Grid Defines Height and also hold content header-->
<Grid>
<Border Background="{DynamicResource TabItemContentPresentBackgroundBrush}"
Margin="0,0,0,5">
<!--Content of TabItem will be rendered-->
<ContentPresenter
x:Name="ContentSite"
Margin="3"
HorizontalAlignment="Left"
VerticalAlignment="Center"
RecognizesAccessKey="True"
ContentSource="Header"/>
</Border>
</Grid>
</ControlTemplate>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
try this
<Label Grid.Row="0"
Foreground="AliceBlue"
Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabControl}
, Path=SelectedItem.Header}"/>
You could try and achieve this either using TemplateBinding or using RelativeSource.
TemplateBinding:
<Label Grid.Row="0"
Foreground="AliceBlue"
Content="{TemplateBinding Header}"/>
RelativeSource:
<Label Grid.Row="0"
Foreground="AliceBlue"
Content="{Binding Path=Header, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabItem}}"/>
This isn't using a control template, but demonstrates binding a textbox to the tab header through a view model. Note that I'm using MVVM light (ViewModelBase and Set()), but you can replace with your own INotifyPropertyChanged support if necessary.
<Grid>
<Grid.Resources>
<DataTemplate x:Key="ContentTemplate" DataType="{x:Type Samples:TabBindingViewModel}">
<StackPanel>
<TextBlock Text="{Binding MyContent}"/>
<TextBox Text="{Binding Header}"/>
</StackPanel>
</DataTemplate>
</Grid.Resources>
<TabControl
ContentTemplate="{StaticResource ContentTemplate}"
DisplayMemberPath="Header"
ItemsSource="{Binding Items}" />
</Grid>
public class TabContentToHeaderViewModels : ViewModelBase
{
private readonly ObservableCollection<TabContentToHeaderViewModel> _items;
public TabContentToHeaderViewModels()
{
_items = new ObservableCollection<TabContentToHeaderViewModel>
{
new TabContentToHeaderViewModel(1),
new TabContentToHeaderViewModel(2),
new TabContentToHeaderViewModel(3),
};
}
public IEnumerable<TabContentToHeaderViewModel> Items
{
get { return _items; }
}
}
public class TabContentToHeaderViewModel : ViewModelBase
{
public TabContentToHeaderViewModel() : this(0)
{
}
public TabContentToHeaderViewModel(int n)
{
Header = "I'm the header: " + n.ToString(CultureInfo.InvariantCulture);
MyContent = "I'm the content: " + n.ToString(CultureInfo.InvariantCulture);
}
private string _header;
public string Header
{
get { return _header; }
set { Set(() => Header, ref _header, value); }
}
public string MyContent { get; set; }
}

WPF items not visible when grouping is applied

I'm having this strange issue with my ItemsControl grouping. I have the following setup:
<ItemsControl Margin="3" ItemsSource="{Binding Communications.View}" >
<ItemsControl.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<Grid>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ItemCount, StringFormat='{}[{0}] '}" FontWeight="Bold" />
<TextBlock Grid.Column="1" Text="{Binding Name, Converter={StaticResource GroupingFormatter}, StringFormat='{}Subject: {0}'}" FontWeight="Bold" />
</Grid>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ItemsControl.GroupStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock FontWeight="Bold" Text="{Binding Inspector, Converter={StaticResource NameFormatter}, StringFormat='{}From {0}:'}" Margin="3" />
<TextBlock Text="{Binding SentDate, StringFormat='{}{0:dd/MM/yy}'}" Grid.Row="1" Margin="3"/>
<TextBlock Text="{Binding Message }" Grid.Column="1" Grid.RowSpan="2" Margin="3"/>
<Button Command="vm:CommunicationViewModel.DeleteMessageCommand" CommandParameter="{Binding}" HorizontalAlignment="Right" Grid.Column="2">Delete</Button>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
In my ViewModel, I expose a CollectionViewSource named 'Communications'. I proceed to adding a grouping patter like so:
Communications.GroupDescriptions.Add(new PropertyGroupDescription("Subject"));
Now, the problem i'm experience is the grouping work fine, but I can't see any items inside the groups. What am I doing wrong? Any pointers would be much appreciated.
I can't seem to reproduce the problem - I assume you are using a CollectionViewSource? It might be because you bound to the View property directly.
Here's the C# code I used:
public class Communication
{
public string Subject { get; set; }
public string Body { get; set; }
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var source = (CollectionViewSource)Resources["Communications"];
source.Source = new List<Communication>()
{
new Communication { Subject = "WPF 4.0", Body = "I love what's happening with 4.0"},
new Communication { Subject = "WPF 4.0", Body = "I hear the text rendering is the best feature"},
new Communication { Subject = "Blend 3.0", Body = "Behaviors in Blend 3 change everything"}
};
source.GroupDescriptions.Add(new PropertyGroupDescription("Subject"));
}
}
Here is the XAML - it's the same as yours but with a couple of things removed since I don't have your converters or commands:
<Window
x:Class="GroupStyleDemo.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"
>
<Window.Resources>
<CollectionViewSource x:Key="Communications" />
</Window.Resources>
<Grid>
<ItemsControl Margin="3" ItemsSource="{Binding Source={StaticResource Communications}}" >
<ItemsControl.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<Grid>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ItemCount, StringFormat='{}[{0}] '}" FontWeight="Bold" />
<TextBlock Grid.Column="1" Text="{Binding Path=Name}" FontWeight="Bold" />
</Grid>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ItemsControl.GroupStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Body }" Grid.Column="1" Grid.RowSpan="2" Margin="3"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
After hitting this problem myself I discovered the cause: the template for ItemsControl directly including a panel with IsItemsHost="true".
You must insert an ItemPresenter into your template and set the ItemsControl.ItemsPanel property instead.

Resources