ItemsControl Freezes UI on Element Generation - xaml

I have an ObservableCollection binded to a ItemsControl inside a PivotItem.
I've made it so the ObservableCollection gets items added silently, only triggering the notificationchanged when it's done.
The Problem comes when generating the items. I've tested the codebehin and everything is completed in a timely manner, however the UI freezes when the items are generated.
This is the template for these ItemsControls:
<Style TargetType="ItemsControl">
<Style.Setters>
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="ItemTemplate" Value="{StaticResource TempCell}" />
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<VariableSizedWrapGrid />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
The problem seems to be with ItemTemplate, even if i add an empty control to the DataTemplate associated with it, it freezes the UI. Not if there is no ItemTemplate.
I'm adding several thousands controls, that will all be displayed at once, simple ToggleButtons 25x25 in size.
I've ran very similar code in WPF, before converting it to UWP and had no freezing issues.
The application runs smoothly after the generation process.
On request here's the addition code:
'Keep in mind that the item generation happens in a separate thread
Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() List.Replace(Output))
'That's why it has to replace the old collection with the new one silently
'This code does not produce any bottleneck in WPF
Public Sub Replace(list As IEnumerable(Of T))
If list Is Nothing Then
Throw New ArgumentNullException("list")
End If
_suppressNotification = True
Clear()
For Each item As T In list
Add(item)
Next
_suppressNotification = False
OnCollectionChanged(New Specialized.NotifyCollectionChangedEventArgs(Specialized.NotifyCollectionChangedAction.Reset))
End Sub
'Scratching the code above and just trying this, i get the same result, it freezes the UI as UWP elements are being generated, here they are added one by one, which should cause notificationchanged events to occur.
Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub()
List.Clear()
For Each Item In Output
List.Add(Item)
Next
End Sub)
'These are the items generated, they refer to a global Random, changing it to a local Random, does not impact the freezing one way or the other.
Parallel.For(0, CellsCount, Sub(i) Output.Add(New Cell With {.Color = Color.FromArgb(255, CByte(Random.Next(0, 256)), CByte(Random.Next(0, 256)), CByte(Random.Next(0, 256)))}))

Related

How to apply styles to all inner elements in MAUI on state change

This is basically simple UI that would conditionally render a label with text Triggered - plain in case the ShowContent property of binding is True. (Overly simplified example here but it works and I can see the label toggles).
<Grid>
<Button Click="ChangeState"/>
<ContentView>
<ContentView.Style>
<Style TargetType="ContentView">
<Style.Triggers>
<DataTrigger Binding="{Binding ShowContent}" Value="True" TargetType="ContentView">
<Setter Property="ControlTemplate">
<Setter.Value>
<ControlTemplate>
<Label>Triggered - Plain</Label>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentView.Style>
</ContentView>
</Grid>
There is also a button that would toggle the state of the Grid:
public void ChangeState(object sender, EventArgs e){
this.state = !this.state; // toggle
if(this.state){
VisualStateManager.GoToState(this, VisualStateManager.CommonStates.Selected);
} else {
VisualStateManager.GoToState(this, VisualStateManager.CommonStates.Normal);
}
}
Problem
I am not sure how to apply a different style to the label based on selected state.
If you use VisualStateManager, you need to have a name on the Label. I want to apply selected style in a blanket way on all inner labels.
Also, if we target the label with a name, when the Label is not on the UI (due to state ShowContent being False), GoToState fails with null exception as it cannot find the label.
The best solution seems to be using CSS but that does not support defined colors and dynamic resources (AFAIK).
Any idea what to do?
Update: one possible solution is to apply the state change to all inner elements:
private IList<T> FindAllChildren<T>()
where T : IVisualTreeElement
{
return this.GetVisualTreeDescendants()
.Where(e => e is T)
.Cast<T>()
.ToList();
}
private void ApplyState(string state)
{
VisualStateManager.GoToState(this, state);
FindAllChildren<VisualElement>().ForEach(e => VisualStateManager.GoToState(e, state));
}
public void ChangeState(object sender, EventArgs e){
this.state = !this.state; // toggle
if(this.state){
ApplyState(VisualStateManager.CommonStates.Selected);
} else {
ApplyState(VisualStateManager.CommonStates.Normal);
}
}
You still need to create VisualStateGroup styling for the labels and give labels a specific style/class:
<label class="Selectable">...</label>
<Style class="Selectable" TargetType="Label">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup Name="all">
<VisualState Name="Normal">
<VisualState.Setters>
<Setter Property="Label.TextColor" Value="{DynamicResource Normal_Color}"/>
</VisualState.Setters>
</VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="Label.TextColor" Value="{StaticResource Selected_Color}"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
I recommend that you work around this. Too many bugs, and too different behavior on the different platforms for containers.
Fixing the visual state is one thing. Then you need to fix "IsEnabled" for child problem. After that if you change the visibility, you will notice that on IOS it is doing one thing, on android - another. (You will start losing this visual state from time to time). At some point you will start looking for ways to force the page to redraw itself.
My advice is, for now, give up on this idea. Until those problems are solved. Wasted too many hours trying to make this work for all platforms.
(Some of the issues are 6+ months old, and they keep pushing them to backlog.)
This is me, asking the same thing, a month ago: Pass the VisualState of CollectionView Item VisualElement to its child VisualElements
Edit: So, what work arounds I use.
Besides styles, visual states, data triggers?
ControlTemplates and Messages between ViewModel <-> View.
Control templates are reusable pieces of user interface, and there isn't much you have to do. You can make all VisualElements bind to the same thing, using TemplatedParent as BindingContext of the container.
Messages I use for some sorts of animations (And other special requests). You can in the ViewModel generate a message, that will be handled (or not) by the View. You have very good control over your View, but you do not break MVVM by coupling them.
A Warning: Every work around is parasitic code (you do something the wrong way, because someone else has been doing his job the wrong way). That code sooner or later will have to be deleted/replaced. Mark it with TODO, because it may take huge part of your app, and later it will be hard to find out all usage places. For now test on IOS. It takes much less work to make it work on IOS, then fix Android, than the other way around.

How to reference parent Flyout from Button? [C++/WinRT]

I have a flyout with a cancel button, where I want the "Cancel" click handler to Hide() the parent flyout. The code segment (below) is part of a ListBoxItem, so I can't reference the flyout by x:name="flyout_name".
This means I need to traverse the Visual Tree Hierarchy, but I'm having trouble accessing the parent Controls::Flyout object.
<Button x:Name="DeleteColButton" Content="Delete">
<Button.Flyout>
<Flyout>
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="TabNavigation" Value="Cycle"/>
</Style>
</Flyout.FlyoutPresenterStyle>
<StackPanel>
<TextBlock TextWrapping="Wrap" Text="Are you sure?"/>
<Button Click="DeleteColClickHandler">Yes</Button>
<Button Click="DeleteColCancelClickHandler">Cancel</Button>
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
I can go from the "Cancel" Button to the top-level stackpanel in the flyout, but the next level up is neither Controls::Flyout nor Controls::FlyoutPresenter. I can call panel.GetParent() 11 times after "escaping" the top-level stackpanel, and none of those DependencyObjects show up as Flyout, FlyoutPresenter, StackPanel, ListBoxItem, or ListBox. Is the visual hierarchy of Flyout somehow disconnected from the hierarchy I'm tracing through the XAML?
I've heard that Flyout doesn't have an associated DependencyObject in the visual tree.. Is this really the case? If I try to go top-down, how would I find the DependencyObject of a ListBoxItem?
Should I switch to Dialog?
Edit: I tried to get access to the button for ( Button().Flyout().Hide() ) from the ListBoxItem, but it proved too difficult.
However, using GetOpenPopups() to get the list of open popups - and closing them all - seemed to work. Thank you!
I can go from the "Cancel" Button to the top-level stackpanel in the flyout, but the next level up is neither Controls::Flyout nor Controls::FlyoutPresenter.
For explain this, you need check this document first,
Popups don't exist in the conventional XAML visual tree that begins from the root visual, although they are associated with the app main window. Unless your app maintains a list of all the Popup elements you've created as well as a status (the IsOpen value), it can be difficult to keep track of them. Sometimes you will want to clear all popups prior to initiating another UI action, like navigating the page or displaying a flyout.
Derive from above the flyout will render on the pop's content. so you could use GetOpenPopups method to get it, if you want to hidden it just set the found Popup isopen property as false like the following.
private void DeleteColCancelClickHandler(object sender, RoutedEventArgs e)
{
var popups = VisualTreeHelper.GetOpenPopups(Window.Current);
foreach (var popup in popups)
{
if (popup is Popup)
{
popup.IsOpen = false;
}
}
}
And the other way is get flyout with Button Flyout Property
var flyout = DeleteColButton.Flyout;
flyout.Hide();
C++/WinRT
auto popups = VisualTreeHelper::GetOpenPopups(Window::Current());
for (int i = 0; i < popups.Size(); i++)
{
auto popup = popups.GetAt(i);
auto name = get_class_name(popup);
if (get_class_name(popup) == L"Windows.UI.Xaml.Controls.Primitives.Popup")
{
popup.IsOpen(false);
}
}

Sharing styles between several GridView controls

I need to style several GridView throughout my application with the same visual styles. This style includes customizing the ItemsPanel property as well as the GroupStyle property.
My problem is that the GroupStyle property of GridView is not a dependency property. So the code I would have liked to write (see below) does not work.
Do you know a clean way to share a style (including GroupStyle) between several GridViews?
The only thing I can think of is using a GroupStyleSelector but it's kind of stupid since there is no selection to make: it's always the same GroupStyle that's being used. Moreover, I suspect it wouldn't be reflected at design time in VS & Blend.
The code I would love to use:
<GridView
ItemsSource="..."
ItemTemplate="..."
Style="{StaticResource MainMenuStyle}"/>
<Style TargetType="GridView" x:Key="MainMenuStyle">
<Setter Property="ItemsPanel">
<Setter.Value>
...
</Setter.Value>
</Setter>
<Setter Property="GroupStyle">
<Setter.Value>
<GroupStyle>
...
</GroupStyle>
</Setter.Value>
</Setter>
</Style>
I've got a magical happy solution.
You can create a custom Attached Property that you set in the Style, and upon setting it internally sets the GroupStyle property on the GridView.
Attached Property:
// Workaround for lack of generics in XAML
public class GroupStyleCollection : Collection<GroupStyle>
{
}
public class GroupStyleHelper
{
public static ICollection<GroupStyle> GetGroupStyle(ItemsControl obj)
{
return (ICollection<GroupStyle>)obj.GetValue(GroupStyleProperty);
}
public static void SetGroupStyle(ItemsControl obj, ICollection<GroupStyle> value)
{
obj.SetValue(GroupStyleProperty, value);
}
public static readonly DependencyProperty GroupStyleProperty =
DependencyProperty.RegisterAttached(
"GroupStyle",
typeof(ICollection<GroupStyle>),
typeof(GroupStyleHelper),
new PropertyMetadata(null, OnGroupStyleChanged));
private static void OnGroupStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsControl itemsControl = d as ItemsControl;
if (itemsControl == null)
return;
RefreshGroupStyle(itemsControl, GetGroupStyle(itemsControl));
}
private static void RefreshGroupStyle(ItemsControl itemsControl, IEnumerable<GroupStyle> groupStyle)
{
itemsControl.GroupStyle.Clear();
if (groupStyle == null)
return;
foreach (var item in groupStyle)
{
itemsControl.GroupStyle.Add(item);
}
}
}
XAML Style:
<Style TargetType="ItemsControl">
<Setter Property="GroupStyleTest:GroupStyleHelper.GroupStyle">
<Setter.Value>
<GroupStyleTest:GroupStyleCollection>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="15" Text="{Binding Path=Name}" Foreground="HotPink"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</GroupStyleTest:GroupStyleCollection>
</Setter.Value>
</Setter>
</Style>
Disclaimer: I'm testing this in WPF rather than WinRT but it should work the same, as far as I can tell. That's also why I'm using an ItemsControl rather than GridView, but the property is ItemsControl.GroupStyle anyway.
I've a solution and that will definitely work as per your question, but though you should decide whether to use that in your case or not.
If you have to make same style of a control in all over the project, then you should make one common folder and in that folder
create one "Custom User Control" and apply all of your style and
customize it however you want.
After that when you need to apply that same kind of style on same control (any grid control) then simply add that customized user
control instead of predefined control
By doing this you'll also achieve MVC architecture and modularity.
I'm developing Windows 8 Metro app in C# with XAML, and in that whenever i wanted this approach then i always use this solution and it always works...
to create custom user control, you should use visual studio & in that right click on project -> add -> new item -> User Control
(Sorry if you couldn't find your solution here, but i think this might help...)

how to set a Viewmodel property when a listbox item is selected

I'm creating a spline designer which requires multiple spline parts.
It contains 2 views (2 UserControls).
The left one is an ItemsControl templated as a Canvas displaying the splines to edit.
The splines parts are UserControls as well.
The right one is a simple ListBox used to select a Spline part.
These two item container are bound to the same ObservableCollection in a ViewModel.
For now, I have a dependencyProperty in the SplinePartVM named IsSelected
What I exactly want to achieve is to modify the DependencyProperty of the SplinePartVM when the SelectedItem is set in the ListBox.
for example, i'd like to do something like this:
<Trigger Property="IsSelected" Value="True">
<Setter Property="{Binding IsSelected}"/>
</Trigger>
because a simple
<ListBox IsSelected="{Binding SelectedItem, Path=IsSelected, Mode=TwoWay}"/>
doesn't work.
I'm a bit lost here...
I found it.
I had to set IsSelected in the style of the ListBoxItem to make it work.

DataTrigger that doesn't undo itself when condition no longer met

Is there a way to do something like the following?
<Style TargetType="{x:Type: TreeViewItem}">
<Style.Triggers>
<DataTrigger Binding="~Complex Binding~" Value="True" DoNotUnset="True">
<Setter Property="IsExpanded" Value="True"/>
</DataTrigger>
</Style.Triggers>
</Style>
What I basically would like is this to be a "No Undo DataTrigger" if you will. When the Value is no longer "True" I don't want it to set "IsExpanded" back to its previous value.
Here is my attempt to do this using enter actions but this also has problems.
<Style TargetType="{x:Type: TreeViewItem}">
<Style.Triggers>
<DataTrigger Binding="~Complex Binding~" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<BeginStoryboard.Storyboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="(IsExpanded)" Duration="00:00:01" FillBehavior="Stop">
<BooleanKeyFrameCollection>
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
</BooleanKeyFrameCollection>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard.Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
First this is insanely verbose but secondly this only works for the duration of the BooleanAnimationUsingKeyFrames. If I change the FillBehavior to "HoldEnd" then it looks correct but now the user can no longer un-expand the treeviewitem by clicks (though oddly enough they still can by using the keyboard).
For those who are wondering: yes I'm trying to expand all items in a tree view by binding because I don't want to build a recursive ItemsGenerator.GetItemContainerFromIndex(i) loop. I'd still like to use a similar "No Undo Datatigger" in other areas of my code.
I would bind the ~Complex Binding~ to a bool in the ViewModel which once set to true is always true.
private bool _onceTrueAlwaysTrue = false;
public bool OnceTrueAlwaysTrue
{
get
{
return _onceTrueAlwaysTrue;
}
set
{
if(value)
{
_onceTrueAlwaysTrue = true;
OnPropertyChanged("OnceTrueAlwaysTrue");
}
}
}
then bind this property to the IsEnabled and you should be fine. If you want to reset it simply make a reset method that sets _onceTrueAlwaysTrue = false;
As for the NoUndo datatrigger, as far as I know there is no such thing. You are gonna have to do some kind of work around every time.
The properties changed by triggers are automatically reset to their previous value when the triggered condition is no longer satisfied. Triggers are optimized for transient states which are expected to change and return to original state, such as IsPressed on Button and IsSelected on ListBoxItem.