Custom Panel with Reorder and animations / transitions - c#

I have a custom class called FluidPanel that extends Panel and overrides methods MeasureOverride and ArrangeOverride. The goal is to create the Google Keep appearence. Ok, it's working fine. (app link)
But, because I'm extending a basic Panel and using it as the ItemsPanelTemplate, I'm missing 2 things: Reorder and some transitions, that simply doens't work out of the box. See code:
<GridView CanReorderItems="True" CanDrag="True" AllowDrop="True">
<GridView.ItemContainerTransitions>
<TransitionCollection>
<EntranceThemeTransition FromVerticalOffset="200" IsStaggeringEnabled="True"/>
<ReorderThemeTransition/>
</TransitionCollection>
</GridView.ItemContainerTransitions>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<local:FluidPanel/><!--custom panel = reorder doesn't work-->
<!--<StackPanel/>--><!--reorder and animations work normally (reorder to see)-->
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<Grid Width="50" Height="50" Background="Red"/>
<Grid Width="50" Height="50" Background="Green"/>
<Grid Width="50" Height="50" Background="Blue"/>
<Grid Width="50" Height="50" Background="Orange"/>
<Grid Width="50" Height="50" Background="Purple"/>
<Grid Width="50" Height="50" Background="Pink"/>
</GridView>
So, the main question is: How to create a custom Panel with Reorder fully working, including animations? (like that offset to the left/right/...)
A second (less important) question is: And with the EntranceThemeTransition working?

I partially found the solution.
Unfortunately it's not as easy as it should be.
For custom Panels, it seems that we have to implement the Reorder manually, listening to the drag & drop events.
Here is an article about it: Extending GridView with Drag and Drop
and here is a simplified code about it.
The reorder animation is added by manually changing the Visual State:
private void OnDragOver(object sender, DragEventArgs e)
{
var item = (e.OriginalSource as FrameworkElement).DataContext as Note;
if (item == null) return;
e.Data.Properties["targetItem"] = item;
var itemContainer = (sender as ItemsControl).ContainerFromItem(item) as Control;
if (itemContainer == null) return;
VisualStateManager.GoToState(itemContainer, "BottomReorderHint", true);
}
But I still hope there is any easier way to do it, giving the fact that a lot of Panels implement it (StackPanel, ItemsWrapGrid, ...).
Still can't get the EntranceThemeTransition to work on the custom panel.
EDIT: workaround to make EntranceThemeTransition works

Related

Why is my Named WPF Shape Inaccesible from Code Behind?

I have an Ellipse in my WPF application. I want to change the colour of its outline whenever it is double clicked. I found this (old) tutorial about making this work by using the available MouseDown event and checking for a ClickCount of two in the event handler. This is the simplest solution to my problem and I'd like to try and get this to work before creating an empty button Control Template.
However, I'm unable to find the clicked ellipse in my code behind file. Supposedly this works in the tutorial, but I'm wondering if I'm missing anything.
Here's the code that contains the ellipse. It is the 3rd column of a grid:
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Grid.Column="3">
<StackPanel Orientation="Vertical" Margin="3,1" Background="GhostWhite">
<ItemsControl Name="FlowLinkItems" ItemsSource="{Binding FlowLinkList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Height="40">
<Ellipse Name="FlowLinkEllipse" Stroke="BlueViolet" Height="38" VerticalAlignment="Center" MouseDown="Ellipse_MouseDown"/>
<TextBlock TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Message}"></TextBlock>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</ScrollViewer>
In the tutorial, the code behind method worked like this:
private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
FlowLinkEllipse.Stroke = "Red";
}
}
And the error I'm seeing is:
The name 'FlowLinkEllipse' does not exist in the current context
If this method is not possible I'm open to suggestions that are as simple as possible (I'm still new to WPF and the only thing my app will handle is this double click).
Note: I do have this line in my code behind and it works fine.
FlowLinkItems.MouseLeftButtonUp += FlowLinkItems_MouseLeftButtonUp;
As #Magus noted, you can't reference an item from code-behind, that is inside a DataTemplate. That should be no problem here, though: sender will contain a reference to the ellipse:
private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e)
{
if (ellipse as sender == null || e.ClickCount < 2)
return;
var ellipse = (Ellipse)sender;
ellipse.Stroke = System.Windows.Media.Brushes.Red;
}

Empty LongListSelector causes infinite ScrollViewer

This is the situation:
I have a datasource that gets filtered by certain attribute (lets call it Checked), into two lists on the viewmodel. Call it New and Old.
New one needs to be displayed into one list, Old one needs to be displayed into the list right under it.
Oh and they need to scroll in unison. So if Old is currently out of screen, it will swim into visibility as the list is swiped up.
I've currently solved this with LongListSelectors like this:
<ScrollViewer VerticalAlignment="Top" VerticalScrollBarVisibility="Auto">
<StackPanel>
<phone:LongListSelector x:Name="NewList" Margin="0,0,0,0" ItemsSource="{Binding New}" SelectionChanged="NewList_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="{Binding Color}" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
<phone:LongListSelector x:Name="OldList" Margin="0,0,0,0" ItemsSource="{Binding Path=Old}" Padding="0,20,0,0">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStyle="Italic" Foreground="{Binding Color}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</StackPanel>
</ScrollViewer>
Two longlistselectors inside a stackpanel inside a scrollviewer. Now it all works absolutely fab while there's something in both of those lists.
However, when one of them has no content whatsoever, it immediately expands to fill the entire height of its parent. In this case... the infinite scrollviewer. Which means that if there's nothing in the New list, there will be absolutely nothing visible on the screen whatsoever and if there's nothing on the New list... I can pretty much scroll infinitely after getting past the New list items.
Do I have any options here? Without programmatically creating a ton of Text fields and then trying to attach events to it, or worse, write my own list control? Standard listboxes don't work because they both scroll separately.
Any ideas?
Having two list controls under each other is a genrally a bad idea, because of ScrollViewers inside ScrolViewers.
I would advise you to use a single LongListSelector without any ScrollViewer around it.
Then create a single collection with old an new items and use an ItemTemplateSelector to style them differently.
The problem you are facing is that by the default when emty LLS is measured it's height as you see is 'infinite'. You are using StacPanel which means that second LLS is under infinite LLS.
The simples solution is to set the Height of LLS:
<phone:LongListSelector x:Name="NewList" Height="300" Margin="0,0,0,0" ItemsSource="{Binding New}" SelectionChanged="NewList_SelectionChanged">
If you can - use a Grid with defined rows instead of StacPanel. If you still want to use StackPanel, you can override the method MeasureOverride() in LLS and make extension.
It should work if you do it like this:
namespace Extensions
{
public class LongListSelectorEx : LongListSelector
{
protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize)
{
if (this.ItemsSource == null)
return new System.Windows.Size(this.Width, 0);
if (this.ItemsSource.Count <= 0)
return new System.Windows.Size(this.Width, 0);
return base.MeasureOverride(availableSize);
}
}
}
Watch out also if you haven't got width defined (the return value cannot be NaN - in that situation put 0 instead this.Width). Of course you will also need to check Height of LLS, bacause if you don't your controls can be pushed off the screen, when there are many items in LLS.
You can also read about this here

How to align RibbonGroup to the right?

I use RibbonControlsLibrary. How to align one RibbonGroup to the right? It should be only one group in tab. All other groups should be aligned to the left.
You cannot align the RibbonGroup to the right. The Ribbon doesn't provide the ability to do this.
What you can do is to align page header items... but I don't know if it's enough for you:
DevExpress
I had the same issue, and I finally found something to do this :
I have 3 RibbonGroupBox. Groupe1 may be aligned on left, Groupe3 may be aligned on right. Groupe2 is just an empty RibbonGroupBox I inserted between Groupe1 and Groupe3.
Code XAML :
<Fluent:Ribbon DockPanel.Dock="Top" Title="{x:Static p:Resources.MiseEnBarre}" x:Name="mainRibbon">
<Fluent:RibbonTabItem x:Name="MainMenu" Header="{x:Static p:Resources.MainMenu}" SizeChanged="MainMenu_SizeChanged">
<Fluent:RibbonGroupBox x:Name="Groupe1">
<Fluent:Button x:Name="autoNest" SizeDefinition="Large" LargeIcon="img\image_bar_Nesting.png" Header="{x:Static p:Resources.MenuAutoNest}" Click="AutoNest_Click" />
<Fluent:Button x:Name="saveFile" SizeDefinition="Large" LargeIcon="img\image_save.png" Header="{x:Static p:Resources.MenuSauvegarder}" Click="Sauvegarder_Click" />
</Fluent:RibbonGroupBox>
<Fluent:RibbonGroupBox x:Name="Groupe2">
</Fluent:RibbonGroupBox>
<Fluent:RibbonGroupBox x:Name="Groupe3">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=AvailableCNClist}" HorizontalAlignment="Left"/>
<TextBlock Grid.Column="1" Text="{Binding Path=AvailableCNClist2}" HorizontalAlignment="Right"/>
</Grid>
</Fluent:RibbonGroupBox>
</Fluent:RibbonTabItem>
</Fluent:Ribbon>
Then to manage the Windows redimensioning, I add on my main window the event SizeChanged="MainWindow_SizeChanged" (In the case your RibbonGroupBox dimensions could also change, just add the same event on them).
private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateAlignRibbon();
}
private void UpdateAlignRibbon()
{
Groupe2.Width = MyWindow.ActualWidth - Groupe1.ActualWidth - Groupe3.ActualWidth;
}
In my case the Groupe3 RibbonGroupBox may change of dimension, so I call UpdateAlignRibbon() from 3 points :
After Initialization of my window(including defining the GroupBoxes content)
When the MainWindow has its dimensions changed
When Groupe1 or Groupe3 have its dimensions changed
Rover, You can try add RibbonGroup between last left RibbonGroup and Right align RibbonGroup and assign size to newly added ribbon related to window size.
example <RibbonGroup Width="400"></RibbonGroup>
it's looks following image
You can sort of hack in alignment but I'd recommend against it.
<r:RibbonGroup Header="This is a Filler Header With No Functionality but to Take Up Space" Visibility="Hidden">
<s:RibbonButton2/>
<s:RibbonButton2/>
<s:RibbonButton2/>
<s:RibbonButton2/>
</r:RibbonGroup>
The customer wanted their logo on the ribbon across the top of the page, but the more you add "false" elements to the bar, the quicker "true" elements will collapse when shrinking the window size.
Try this:
<RibbonTab Header="Home" x:Name="rtabHome" FlowDirection="RightToLeft" >
<RibbonGroup Header="Group">
<TextBlock Text="Example"/>
</RibbonGroup>
</RibbonTab>
Works with FlowDirection="RightToLeft".

Correct approach to make a ListBox Page Navigation using MVVM on Windows Phone

I am building an app for Windows Phone, and in this app I have a list of Movies with Title, Plot and Picture.
I have this list bound to a ListBox with a custom DataTemplate for the items showing the data. I also created a second page to show the details of each movie.
My problem now is the navigation between these pages. I'm using MVVM to build the applications and most of the approaches I've found searching on internet is to use the OnSelectionChanged event in the code-behind, but it goes agains what I want, that is to use MVVM.
Other approach I've seen, which is the one I'm trying, is to bind the SelectedItem to a property in the ViewModel, but I can't make it change the property, it seems that I cannot select an item in the listbox. Also, I don't have the visual feedback when I press one of the items in my listbox, like the feedback we have in the settings menu of the phone for example.
The code I'm using in the listbox is:
<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Movies}" SelectedItem="{Binding SelectedMovieItem}" SelectionMode="Single" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<!--Replace rectangle with image-->
<Rectangle Height="50" Width="50" Fill="#FFE5001b" Margin="12,0,9,0"/>
<StackPanel Width="311">
<TextBlock Text="{Binding Name}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#000" />
<!--<TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>-->
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Another approach I've seen is to use the INavigationService to achieve this, I found this article: http://windowsphonegeek.com/articles/MVVM-in-real-life-Windows-Phone-applications-Part1
I read the parts one and two, but I couldn't understand this one works.
So, what I want to know is whether the approach I'm using is the correct to make a page navigation, or if there is a better way using MVVM to do this with visual feedback on the listbox.
Why is handling Event in the code behind against MVVM? Handling events interaction is part of the UI. Of course you won't all you code logic there. But you are trying just to go to the next page. I do something like this :
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected index is -1 (no selection) do nothing
if (MainListBox.SelectedIndex == -1)
return;
// Navigate to the new page
NavigationService.Navigate(new Uri("/Views/detailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
// Reset selected index to -1 (no selection)
MainListBox.SelectedIndex = -1;
}

How to implement "Mega Menus" in WPF?

I'm trying to implement "Mega Menu" style menus using WPF. To see examples of mega menus in web design, see here.
So far, I've tried creating a similar interface by using TextBlocks as the highest level of the menu, and then using the mouse hover event to display an additional window that appears positioned below the text block. This is cumbersome and inflexible, future changes would require adding/removing TextBlocks dynamically.
I have considered using the WPF Menu control, because I know the styles can be dramatically modified, but I haven't seen any way to produce multi-column layouts with the hierarchical model that the Menu control uses.
Is there a better way to do this? Am I going to have to stick with custom windows and relative positioning? Can someone point me to an example of this that has already been implemented?
Instead of using custom Windows and positioning, you could use a Popup control. Your can use the StaysOpen=false setting to have it close when the user clicks off-screen.
If you can settle for clicking a menu item instead of hovering, the following custom control will work:
[TemplatePart(Name="PART_HoverArea", Type=typeof(FrameworkElement))]
[TemplatePart(Name="PART_Popup", Type=typeof(Popup))]
public class MegaMenuItem : HeaderedContentControl
{
private FrameworkElement hoverArea;
private Popup popup;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Unhook old template
if (hoverArea != null)
{
hoverArea.PreviewMouseUp -= ShowPopupOnMouseDown;
}
hoverArea = null;
popup = null;
if (Template == null)
return;
// Hook up new template
hoverArea = (FrameworkElement)Template.FindName("PART_HoverArea", this);
popup = (Popup)Template.FindName("PART_Popup", this);
if (hoverArea == null || popup == null)
return;
hoverArea.PreviewMouseUp += ShowPopupOnMouseDown;
}
private void ShowPopupOnMouseDown(object sender, MouseEventArgs e)
{
popup.PlacementTarget = hoverArea;
popup.Placement = PlacementMode.Bottom;
popup.StaysOpen = false;
popup.IsOpen = true;
}
}
You would need a style to display it - something like this. Note the PART_ template part names:
<Style TargetType="WpfApplication14:MegaMenuItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="WpfApplication14:MegaMenuItem">
<Grid>
<Border Name="PART_HoverArea" Background="#fb9c3b" BorderBrush="White" BorderThickness="0,0,1,0">
<ContentPresenter Content="{TemplateBinding Header}" />
</Border>
<Popup
Name="PART_Popup"
PlacementTarget="{Binding ElementName=HoverArea}"
>
<Border MinWidth="100" MaxWidth="400" MinHeight="40" MaxHeight="200" Background="#0d81c3">
<ContentPresenter Content="{TemplateBinding Content}" />
</Border>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The XAML for your menu would then be:
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<WpfApplication14:MegaMenuItem Header="Parent 1">
<WrapPanel Margin="5">
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
</WrapPanel>
</WpfApplication14:MegaMenuItem>
<WpfApplication14:MegaMenuItem Header="Parent 2">
<WrapPanel Margin="5">
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
</WrapPanel>
</WpfApplication14:MegaMenuItem>
</StackPanel>
Making the menu appear on hover is much harder, because of the way Popups steal focus (you can show the menu, but you can't easily hide it if they mouse over another menu). For that a custom window might work better.
You could use a HeaderedItemsControl and swap out the Panel to suit your needs; by default it uses a StackPanel however a WrapPanel may suit you better. The pop out and mouse over behavior do not exist by default and would need to be implemented.
A more robust approach would be to leverage a custom Expander; as it provides the pop out behavior you are after and the linked to walkthrough provides the mouse over behavior.
I wonder if the Ribbon control can be retrofitted to do this? It provides tabs, labels, columns and all that.
Please use this UI design sparingly and make sure that it only opens and closes when the user specifically requests such. It's tremendously annoying when a popup mega-menu appears over a website I'm viewing, and I can't get it to close, except for when I want to click on it and it goes away.
Custom windows and relative position are essentially how the WPF Menu/MenuItem control works... but as you've found, it's non-trivial. Best bet would be to retemplate the Menu/MenuItem controls to meet your need.

Categories