listbox inside ScrollViewer - freeze program - c#

I need some advice. We noticed unusual behavior within the ScrollViewer. I have a StackPanel with whom I am more items including ListBox when the StackPanel placed in a ScrollViewer, when loading data to the listbox, a program for a brief moment freezes. When I am alone ListBox but everything works normally, no freezing of the program.
Here is my code:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel x:Name="tStack" >
<Grid Height="300">
</Grid>
<Grid Height="300">
</Grid>
<ListBox x:Name="ListBox1" ItemsSource="{Binding AlbumsCvs.View, IsAsync=True}"
Style="{StaticResource ListBoxAlbumsTracksStyles}"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingStackPanel.VirtualizationMode="Recycling" >
<ListBox.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource AlbumsHeader}" />
</ListBox.GroupStyle>
</ListBox>
</StackPanel>
</ScrollViewer>
<Style x:Key="ListBoxAlbumsTracksStyles" TargetType="{x:Type ListBox}">
<Setter Property="Padding" Value="0,0,0,0" />
<Setter Property="Margin" Value="0,0,0,0" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate >
<DockPanel>
<Border Background="#00000000"
Height="36"
Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}">
<DockPanel>
<TextBlock x:Name="TrackNumber"
DockPanel.Dock="Left" Margin="2,0,5,0"
Text="{Binding TrackNumber}"
VerticalAlignment="Center"
FontSize="13"
MinWidth="17"
Foreground="Black"/>
<DockPanel>
<TextBlock DockPanel.Dock="Left"
Text="{Binding TrackTitle}"
TextAlignment="Left"
FontSize="13"
VerticalAlignment="Center"
HorizontalAlignment="Stretch"
TextTrimming="CharacterEllipsis"
Margin="0,0,2,0"/>
<TextBlock DockPanel.Dock="Right"
Text="{Binding Duration}"
VerticalAlignment="Center"
HorizontalAlignment="Stretch"
TextTrimming="CharacterEllipsis"
Margin="0,0,10,0"
FontSize="13" TextAlignment="Right"/>
</DockPanel>
</DockPanel>
</Border>
</DockPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- GroupItem -->
<Style x:Key="AlbumsHeader" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}" Background="#00000000">
<StackPanel Margin="0,0,0,15">
<StackPanel>
<TextBlock Text="{Binding AlbumName}"
DataContext="{Binding Items}"
Margin="0,5,0,0"
HorizontalAlignment="Stretch"
FontSize="20"
FontWeight="Light"
TextTrimming="CharacterEllipsis"
Foreground="Black"/>
<TextBlock Text="{Binding IdAlbum}"
DataContext="{Binding Items}"
Margin="0,0,0,10"
HorizontalAlignment="Stretch"
TextTrimming="CharacterEllipsis"
Foreground="Black"/>
</StackPanel>
<ItemsPresenter HorizontalAlignment="Stretch"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
code behind:
private async Task AlbumsArtistInformation()
{
if (string.IsNullOrEmpty(ArtistName))
return;
ObservableCollection<AlbumsArtistCollections> _albumsArtistCollections =
new ObservableCollection<AlbumsArtistCollections>();
try
{
var search = await spotifyDataService.GetArtists(ArtistName);
if (search == null) throw new ArgumentNullException(nameof(search));
foreach (var _artist in search.Artists.Items.Take(1))
{
this.IdArtist = _artist.Id;
}
var _artistAlbum = await spotifyDataService.GetArtistsAlbumsAsync(this.IdArtist, AlbumType.All);
if (_artistAlbum == null) throw new ArgumentNullException(nameof(_artistAlbum));
_albumsArtistCollections = _artistAlbum;
}
finally
{
// Unbind to improve UI performance
Application.Current.Dispatcher.Invoke(() =>
{
this.Albums = null;
this.AlbumsCvs = null;
});
Application.Current.Dispatcher.Invoke(() =>
{
this.Albums = _albumsArtistCollections;
});
Application.Current.Dispatcher.Invoke(() =>
{
// Populate CollectionViewSource
this.AlbumsCvs = new CollectionViewSource { Source = this.Albums };
//Group by Album if needed
this.AlbumsCvs.GroupDescriptions.Add(new PropertyGroupDescription("IdAlbum"));
});
}
}
Does anyone know how to solve this problem.

Vertically oriented StackPanel provides an unbounded available space for the the ListBox, when it calls MeasureOverride(Size availableSize) method, during layout. Therefore, the ListBox (which by default uses virtualization) should create the whole items and this is why you program freezes for a moment.
Therefore, use a DockPanel instead:
<DockPanel x:Name="tStack" LastChildFill="True" >
<Grid DockPanel.Dock="Top" Height="300">
</Grid>
<Grid DockPanel.Dock="Top" Height="300">
</Grid>
<ListBox DockPanel.Dock="Bottom" x:Name="ListBox1" ItemsSource="{Binding AlbumsCvs.View, IsAsync=True}"
Style="{StaticResource ListBoxAlbumsTracksStyles}"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingStackPanel.VirtualizationMode="Recycling" >
<ListBox.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource AlbumsHeader}" />
</ListBox.GroupStyle>
</ListBox>
</DockPanel>
LastChildFill is true by default. The ListBox should be the last element, in order to fill the space.
As another option, you can set the Height of the ListBox and put the DockPanel in a ScrollViewer or you can consider a Grid with splitters as another option.

Related

Change Text of Textblock in controltemplate

I have a list of items which a user can select and I would like to add an explanation text. So far I have this code
<TabItem Name="TabItem02" Header="">
<ListBox Name="listBox01" VerticalAlignment="Stretch" SelectionMode="Multiple" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedValuePath="Content">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<CheckBox Margin="5,2" IsChecked="{TemplateBinding IsSelected}" Grid.Column="0" VerticalAlignment="Top">
<ContentPresenter VerticalAlignment="Center">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<TextBlock Text="{TemplateBinding Content}" TextWrapping="Wrap" />
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</CheckBox>
<Expander Header="Explanation" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" FlowDirection="RightToLeft">
<TextBlock TextWrapping="Wrap" FlowDirection="LeftToRight"/>
</Expander>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBoxItem Name="List1Item01" IsEnabled="False"/>
<ListBoxItem Name="List1Item02" IsEnabled="False"/>
<ListBoxItem Name="List1Item03" IsEnabled="False"/>
<ListBoxItem Name="List1Item04" IsEnabled="False"/>
<ListBoxItem Name="List1Item05" IsEnabled="False"/>
</ListBox>
</TabItem>
And at the moment I am changing the content of each ListBox through a ressourcefile with this code-behind
foreach (ListBox listBox in ListBoxes)
{
foreach (ListBoxItem item in listBox.Items) item.Content = resourceManager.GetString(item.Name);
}
I would like to change the text of the second TextBlock (the one in the Expander) according to the ListBoxItem it belongs to as easy as the ListBox content itself through the ressourcefile. I would prefer not to create a separate Expander + TextBlock for each ListBoxItem with a separate name.
So if anyone has a solution for my problem, I would really appreciate that.

WPF: Get control from ListView DataTemplate in Code Behind

I've created a ListView with a selfmade ItemTemplate, that is quite nested:
<ListView x:Name="QuestionListView" ItemsSource="{Binding QuestionList, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" Background="#afafaf" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,5,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="8*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Border Grid.Column="0" CornerRadius="15,0,0,15" BorderBrush="Gray" BorderThickness="0,0,1,0" Background="#676767" />
<Border Grid.Column="1" BorderBrush="Gray" BorderThickness="0,3,1,3" Background="#8f8f8f" />
<Border Grid.Column="2" CornerRadius="0,15,15,0" BorderThickness="1" BorderBrush="Gray" Background="#676767" />
<Label Content="{Binding ID}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="40" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontWeight="Bold" Foreground="Beige" />
<!--This is the TextEditor, I need in my Code behind-->
<Viewbox Grid.Column="1">
<avalonEdit:TextEditor xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit" Name="textEditor" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Stretch" Width="600" FontSize="30" Background="Transparent" BorderBrush="Transparent" Foreground="Beige" PreviewLostKeyboardFocus="RichTextBox_PreviewLostKeyboardFocus" FontFamily="Consolas">
<i:Interaction.Behaviors>
<beh:AvalonEditBehaviour GiveMeTheText="{Binding TextQuestion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</i:Interaction.Behaviors>
</avalonEdit:TextEditor>
</Viewbox>
<!--<TextBlock Grid.Column="1" IsHitTestVisible="False" FontSize="25" FontWeight="Bold" Foreground="LightGray" Text="Your question here" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding TextQuestion, Mode=TwoWay}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>-->
<StackPanel Orientation="Horizontal" Grid.Column="2" HorizontalAlignment="Center">
<Button Margin="10,0,5,0" Width="40" Height="40" Background="Gray" Command="{Binding EditCommand}" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave">
<Image Source="{Binding EditImage}" />
</Button>
<Button Margin="5,0,10,0" Width="40" Height="40" Background="Gray" Command="{Binding DeleteCommand}">
<Image Source="{Binding DeleteImage}" />
</Button>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListView>
Now I want to get the TextEditor textEditor in my code behind, because I need it for the "Intellisense" window, I am customizing.
So I have this in my Code behind:
public partial class QuestionListUC : UserControl
{
TextEditor editor;
public QuestionListUC()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
var template = QuestionListView.Template;
editor = (TextEditor)template.FindName("textEditor", QuestionListView);
}
}
But the FindName-Method outputs nothing for me, the variable "editor" is null.
What am I doing wrong here?
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() => {
var template = QuestionListView.ItemTemplate;
editor = (TextEditor)template.FindName("textEditor",
QuestionListView);
}), DispatcherPriority.DataBind);
}
This should work
The most important change is
var template = QuestionListView.ItemTemplate;
The Dispatcher just delays the action until the data binding has been done, so the ItemTemplate should not be null
I managed to get a ViewBox around the Editor and then just use it's child. now I have the control in my CB

LostFocus does'nt work TextBox when selecting a TreeviewItem

Hi I need to solve a problem between the TextBox and the treeview. When I select the TreeView after the TextBox I don't receive the LostFocus Event (for the TextBox) why?
I have tried to play a lot with Focusable and the focusableManager but .... it didn't helped me.
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Visibility="{Binding VariableA, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BoolToHiddenConverter}}
<TextBox Width="78" FocusManager.IsFocusScope="True"
PreviewTextInput="HatchingDistanceBox_PreviewTextInput"
Name="TextBoxAWhoShouldLostFocus" BorderThickness="0.5"
BorderBrush="White" MinHeight="30" Height="30" Text="{Binding SelectedFamille.VariableA}"
utilities:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text">
</TextBox>
<TreeView Name="TreeView_After" ItemsSource="{Binding FirstGeneration}" Focusable="True" Grid.ColumnSpan="3" Grid.Row="2" Grid.Column="0" AllowDrop="True" Background="#282828" Margin="15, 0,0,0" >
<TreeView.Style>
<Style TargetType="{x:Type TreeView}">
<EventSetter Event="GotFocus" Handler="TreeViewItem_GotFocus"></EventSetter>
</Style>
</TreeView.Style>
<i:Interaction.Behaviors>
<utilities:TreeViewSelectionBehavior SelectedItem="{Binding SelectedFamille}"/>
</i:Interaction.Behaviors>
<TreeView.Resources>
<DataTemplate x:Key="NormalTemplate">
<StackPanel Orientation="Horizontal" Name="StrategyNamePanel" Mouse.PreviewMouseDown="StrategyNamePanel_MouseDown" Width="200" Background="#282828" Focusable="True" FocusManager.IsFocusScope="True">
<TextBox Name="StrategyNameBox" FontWeight="Normal" FocusManager.IsFocusScope="True" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=Explicit}" MinHeight="30" Height="30" BorderThickness="0" utilities:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"></TextBox>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="EditTemplate">
<StackPanel Orientation="Horizontal" Name="NamePanel" Focusable="True" Mouse.PreviewMouseDown="NamePanel_MouseDown" Width="200" Background="{StaticResource DarkGrey}" FocusManager.IsFocusScope="True">
<TextBox Name="NameBox" FontWeight="Normal" BorderBrush="{StaticResource DarkOrange}" FocusManager.IsFocusScope="True" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=Explicit}" MinHeight="30" Height="30" utilities:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text" ></TextBox>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="GotFocus" Handler="TreeViewItem_GotFocus"></EventSetter>
<EventSetter Event="TreeViewItem.DragOver" Handler="TreeView_After_DragOver"/>
<EventSetter Event="TreeViewItem.Drop" Handler="TreeView_After_Drop"/>
<EventSetter Event="TreeViewItem.MouseMove" Handler="TreeView_After_MouseMove"/>
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
The LostFocus from the textbox work when I click everywhere except in the TreeView
2) The lostFocus work if I first select a parent in the treeView and then a Treeview Item.
3)When I first select a treeViewItem and Then an Another treeViewItem there is no more LostFocus Event.
Why????

WPF ListView inside ListView not scrolling when mouse over the inner ListView

I have a ListView inside a ListView and when the mouse is over the inner ListView, the outer ListView stops scrolling.
The scroll works when the mouse is over the items in the outer ListView and when the mouse is over the scroll bar.
XAML:
<Window x:Class="ListViewInsideListViewNoteScrolling.CheckForUpdatesView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CheckForUpdatesView" Height="300" Width="500">
<Grid>
<ListView Grid.Row="0" Margin="20 10" BorderThickness="0" BorderBrush="Transparent"
HorizontalAlignment="Stretch"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="False"
ItemsSource="{Binding VersionsDetails}"
ItemContainerStyle="{StaticResource CheckForUpdatesListView}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="400">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" FontWeight="Bold">
<Run Text="Version "/> <Run Text="{Binding Number}"/>
</TextBlock>
<TextBlock Grid.Row="1" Text="{Binding Description}" TextWrapping="Wrap"/>
<ListView Grid.Row="2" Margin="10 0 0 0" BorderThickness="0" BorderBrush="Transparent"
ItemsSource="{Binding Details}"
ItemContainerStyle="{StaticResource CheckForUpdatesListView}">
<ListView.ItemTemplate>
<DataTemplate>
<BulletDecorator Margin="4">
<BulletDecorator.Bullet>
<Ellipse Height="5" Width="5" Fill="Black"/>
</BulletDecorator.Bullet>
<TextBlock TextWrapping="Wrap" Text="{Binding}" Width="350"></TextBlock>
</BulletDecorator>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<!--<TextBlock Grid.Row="3" Text="{Binding Details, Converter={StaticResource ListToTextConverter}}" TextWrapping="Wrap"/>-->
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
Style:
<Style x:Key="CheckForUpdatesListView" TargetType="ListViewItem">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Border" Padding="0" BorderThickness="0" SnapsToDevicePixels="true" Background="Transparent">
<ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="Border" Property="Background" Value="Transparent"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
VersionsDetails is a List<VersionInfo>
public class VersionInfo
{
public string Number { get; set; }
public string Description { get; set; }
public List<string> Details { get; set; }
}
One possible solution is, instead of the inner ListView, to use this line
<TextBlock Grid.Row="3" Text="{Binding Details, Converter={StaticResource ListToTextConverter}}" TextWrapping="Wrap"/>
which will convert my list into a bulleted string, but the styling is better with the ListView.
I am also open to suggestions for using other Wpf controls/elements to solve this issue.
A nice solution would be to create a behavior to ignore mouse wheel.
1> Import System.Windows.Interactivity
2> Create the behavior:
public sealed class IgnoreMouseWheelBehavior : Behavior<UIElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewMouseWheel += AssociatedObjectPreviewMouseWheel;
}
protected override void OnDetaching()
{
AssociatedObject.PreviewMouseWheel -= AssociatedObjectPreviewMouseWheel;
base.OnDetaching();
}
private void AssociatedObjectPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
var mouseWheelEventArgs = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
{
RoutedEvent = UIElement.MouseWheelEvent
};
AssociatedObject.RaiseEvent(mouseWheelEventArgs);
}
3> Attached the behavior to your inside ListView
<ListView Grid.Row="2" Margin="10 0 0 0" BorderThickness="0"
ItemsSource="{Binding Details}"
ItemContainerStyle="{StaticResource CheckForUpdatesListView}">
<i:Interaction.Behaviors>
<local:IgnoreMouseWheelBehavior />
</i:Interaction.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<BulletDecorator Margin="4">
<BulletDecorator.Bullet>
<Ellipse Height="5" Width="5" Fill="Black"/>
</BulletDecorator.Bullet>
<TextBlock TextWrapping="Wrap" Text="{Binding}" Width="350"></TextBlock>
</BulletDecorator>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Inspired by this close question : Bubbling scroll events from a ListView to its parent

How to switch StackPanel items' Panel.ZIndex value with a Control outside?

Maybe this is a stupid asking, but I just wonder how to design this kind of layout:
first of all, I have a MenuList ObservableCollection. So I have to put these menus in to a stackPanel like this:
<Window.Resources>
<DataTemplate x:Key="MenuItemTemplate">
<Button Content="{Binding ContentText}" Panel.ZIndex="{Binding PIndex}" Padding="10" FontSize="20"/>
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Menus}" ItemTemplate="{StaticResource MenuItemTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
so it looks like this:
after a while, there's a new bar under this menu added in:
<ItemsControl ItemsSource="{Binding Menus}" ItemTemplate="{StaticResource MenuItemTemplate}">
.......
</ItemsControl>
<Border Background="Green" VerticalAlignment="Top" Panel.ZIndex="10" Height="30" Margin="0,81,0,0"/>
Now it's look like this:
The requirment is, if a button selected, it should on the top of the bar, other unselected buttons should be covered by the bar:
But the buttons' are in a StackPanel, so they're all based on StackPanel's ZIndex.
My question is, how to design such layout in xaml?
I think using the renderTransform is better. No need to hard code PIndex in xaml. See below.
<DataTemplate x:Key="MenuItemTemplate">
<Button Content="{Binding}" Padding="10" FontSize="20" Height="30" Width="100">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1" ScaleY="1.2"></ScaleTransform>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</DataTemplate>
<Border Background="Green" VerticalAlignment="Top" Height="30" Margin="0,150,0,0"/>
<ItemsControl ItemsSource="{Binding Menus}" ItemTemplate="{StaticResource MenuItemTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Code behind:
public ObservableCollection<string> Menus { get; set; }
EDIT:
<DataTemplate x:Key="MenuItemTemplate">
<Button Content="{StaticResource image1}" Height="30" Width="100">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Border x:Name="Border" Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}" Background="Orange">
</Border>
<ContentPresenter ContentSource="Content" HorizontalAlignment="Stretch" VerticalAlignment="Top"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="RenderTransform" TargetName="Border">
<Setter.Value>
<ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1" ScaleY="1.2"></ScaleTransform>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</DataTemplate>
If the bar is literally just a green bar, you can also put it on the DataTemplate as a separate Stackpanel from the button, and then put a Style.Trigger on the Button's stackpanel to increase the ZIndex OnMouseOver. The bar would look seamless even if it is just repeating.
So instead of:
<DataTemplate x:Key="MenuItemTemplate">
<Button Content="{Binding ContentText}" Panel.ZIndex="{Binding PIndex}" Padding="10" FontSize="20"/>
</DataTemplate>
You will have
<DataTemplate x:Key="MenuItemTemplate">
<Grid>
<StackPanel >
<StackPanel.Style>
<Style TargetType="StackPanel" >
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Panel.ZIndex" Value="3"></Setter>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Panel.ZIndex" Value="1"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
<Button Width="100" Height="100" Content="{Binding ContentText}" Padding="10" FontSize="20" />
</StackPanel>
<StackPanel Panel.ZIndex="2">
<Border Background="Green" VerticalAlignment="Top" Height="30"/>
</StackPanel>
</Grid>
</DataTemplate>
(This doesn't look quite perfect if you run it, but you get the idea)
Dockpanel as our ItemPanelTemplate is the right choice.
Use a Grid with Button and Rectangle (for bottom border) as DataTemplate to show Menu items.
Don't apply margin in DataTemplate's Grid in step2 above. Instead use Grid Padding, Button margin for spacing.
DataTemplate :
<DataTemplate x:Key="MenuItemTemplate">
<Grid Background="DodgerBlue">
<Button Margin="5 5 5 0" HorizontalAlignment="Left" Panel.ZIndex="1" Content="{Binding ContentText}" Padding="1" Width="75" GotKeyboardFocus="Button_GotKeyboardFocus" LostKeyboardFocus="Button_LostKeyboardFocus"/>
<Rectangle Panel.ZIndex="2" Fill="BurlyWood" Height="5" Margin="0 25 0 0"/>
</Grid>
</DataTemplate>
ItemPanelTemplate :
<ItemsPanelTemplate>
<DockPanel Height="30" LastChildFill="True"/>
</ItemsPanelTemplate>
Use the below code as is :
<ItemsControl Panel.ZIndex="10" VerticalAlignment="Top" ItemsSource="{Binding Menus}" ItemTemplate="{DynamicResource MenuItemTemplate}" Margin="0">
<ItemsControl.Resources>
<DataTemplate x:Key="MenuItemTemplate">
<Grid Background="DodgerBlue">
<Button Margin="0" HorizontalAlignment="Left" Panel.ZIndex="1" Content="{Binding ContentText}" Padding="1" Width="75" GotKeyboardFocus="Button_GotKeyboardFocus" LostKeyboardFocus="Button_LostKeyboardFocus"/>
<Rectangle Panel.ZIndex="2" Fill="BurlyWood" Height="5" Margin="0 25 0 0"/>
</Grid>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<DockPanel Height="30" LastChildFill="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Code-Behind
public IList Menus { get; set; }
public Window1()
{
InitializeComponent();
Menus = new[] { new { ContentText = "Menu1" }, new { ContentText = "Menu2" }, new { ContentText = "Menu3" } };
this.DataContext = this;
}
private void Button_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
Panel.SetZIndex((Button)e.OriginalSource, 12);
}
private void Button_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
Panel.SetZIndex((Button)e.OriginalSource, 1);
}

Categories

Resources