I have two buttons placed horizontally. They are inside a grid. This grid containing two buttons has width 370. When the text on the button becomes large, it needs width more than 370. So what I want to do is, instead of placing then horizontally, I want to place them vertically dynamically when text will start cropping. Basically, I want auto-reflow behavior inside this grid for these two buttons based on width of the grid (not based on width of main window). So I want them to fit in 370 width and if they cannot, I want them to place themselves vertically. How can I achieve this?
I explored GridView but it will show buttons inside the box that comes with GridView so I do not want extra UI that comes with GridView unless we have an option to hide it?
I checked AdaptiveTrigger but that is based on width of window not of the control (grid in this case)
<Grid
Grid.Row="2"
Margin="0,36,0,28"
Width="370"
HorizontalAlignment="Left"
VerticalAlignment="Bottom">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid
Grid.Column="0"
CornerRadius="3">
<Button
MinWidth="118"
MinHeight="30"
HorizontalAlignment="Left"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
AutomationProperties.Name="{x:Bind ViewModel.PrimaryActionAutomationName, Mode=OneWay}"
BorderThickness="1"
Click="{x:Bind ViewModel.InvokePrimaryAction}"
Content="{x:Bind ViewModel.PrimaryAction, Mode=OneWay}"
CornerRadius="3"
Style="{StaticResource AccentButtonStyle}" />
</Grid>
<Grid
Grid.Column="1"
CornerRadius="3"
Margin="32,0,0,0">
<HyperlinkButton
AutomationProperties.Name="{x:Bind ViewModel.SecondaryLinkAutomationName, Mode=OneWay}"
AutomationProperties.AutomationId="{Binding AutomationId, ConverterParameter=HyperlinkButton, Converter={StaticResource AutomationIdConverter}}"
Content="{x:Bind ViewModel.SecondaryText, Mode=OneWay}"
FontSize="14"
Margin="0,0,0,0"
Style="{StaticResource HyperlinkButtonStyle}"
NavigateUri="{x:Bind ViewModel.SecondaryLink, Mode=OneWay}" />
</Grid>
</Grid>
For your scenario, I'd suggest you custom a StateTrigger based on the StateTriggerBase Class to monitor the width of the Grid and apply visual states based on the width.
I've made a simple sample that you could refer to.
ControlSizeTrigger:
public class ControlSizeTrigger : StateTriggerBase
{
//private variables
private double _minHeight, _minWidth = -1;
private FrameworkElement _targetElement;
private double _currentHeight, _currentWidth;
//public properties to set from XAML
public double MinHeight
{
get
{
return _minHeight;
}
set
{
_minHeight = value;
}
}
public double MinWidth
{
get
{
return _minWidth;
}
set
{
_minWidth = value;
}
}
public FrameworkElement TargetElement
{
get
{
return _targetElement;
}
set
{
if (_targetElement != null)
{
_targetElement.SizeChanged -= _targetElement_SizeChanged;
}
_targetElement = value;
_targetElement.SizeChanged += _targetElement_SizeChanged;
}
}
//Handle event to get current values
private void _targetElement_SizeChanged(object sender, SizeChangedEventArgs e)
{
_currentHeight = e.NewSize.Height;
_currentWidth = e.NewSize.Width;
UpdateTrigger();
}
//Logic to evaluate and apply trigger value
private void UpdateTrigger()
{
//if target is set and either minHeight or minWidth is set, proceed
if (_targetElement != null && (_minWidth > 0 || _minHeight > 0))
{
//if both minHeight and minWidth are set, then both conditions must be satisfied
if (_minHeight > 0 && _minWidth > 0)
{
SetActive((_currentHeight >= _minHeight) && (_currentWidth >= _minWidth));
}
//if only one of them is set, then only that condition needs to be satisfied
else if (_minHeight > 0)
{
SetActive(_currentHeight >= _minHeight);
}
else
{
SetActive(_currentWidth >= _minWidth);
bool bbb = _currentWidth >= _minWidth;
Debug.WriteLine("Widthtrigger :" + bbb);
}
}
else
{
SetActive(false);
}
}
}
MainPage.xaml:
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ControlSizeStates">
<VisualState x:Name="SizeChange">
<VisualState.StateTriggers>
<local:ControlSizeTrigger MinWidth="800" TargetElement="{x:Bind Path=MyStackPanel}" />
<!--<AdaptiveTrigger MinWindowHeight="500" />-->
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MyStackPanel.Background" Value="Red" />
<Setter Target="MyStackPanel.Orientation" Value="Horizontal" />
<Setter Target="MyButton.Foreground" Value="Black" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<StackPanel x:Name="MyStackPanel" Width="100" Height="200" Background="AliceBlue" Orientation="Vertical">
<Button x:Name="MyButton" Foreground="Red" Content="Click" Click="Button_Click"/>
<Button x:Name="MyButton2" Foreground="Red" Content="Click" />
</StackPanel>
</Grid>
MainPage.cs:
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyStackPanel.Width = 1100;
}
Related
In our UWP app the DataTemplate for MyListView is set in the code behind to either DataTemplateA or DataTemplateB in Page.Resources. Each data template contains a grid (TopGrid) which contains a DisplayGridButton and another grid (DisplayGrid).
DisplayGrid contains SecondListView and a HideGridButton
DisplayGridButton should show DisplayGrid. HideGridButton should collapse DisplayGrid.
The XAML is
<Page.Resources>
<DataTemplate x:Key="DataTemplateA">
<Grid Name="TopGrid">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBox/>
<Button Name="DisplayGridButton" Content="Show" Margin="10,0" Click="DisplayGridButton_Click"/>
</StackPanel>
<Grid Name="DisplayGrid" Grid.Row="1" Visibility="Collapsed">
<StackPanel>
<Button Name="HideGridButton" Content="Hide" Click="HideGridButton_Click"/>
<ListView Name="SecondListView">
<ListView.ItemTemplate>
<DataTemplate >
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
</Grid>
</DataTemplate>
<DataTemplate x:Key="DataTemplateB">
<Grid Name="TopGrid">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBox/>
<Button Name="DisplayGridButton" Content="Show" Margin="10,0" Click="DisplayGridButton_Click"/>
</StackPanel>
<Grid Name="DisplayGrid" Grid.Row="1" Visibility="Collapsed">
<StackPanel>
<Button Name="HideGridButton" Content="Hide" Click="HideGridButton_Click"/>
<ListView Name="SecondListView">
<ListView.ItemTemplate>
<DataTemplate >
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
</Grid>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView Name="MyListView">
</ListView>
</Grid>
DataTemplateA or DataTemplateB is set in the code behind.
if (condition)
{
MyListView.ItemTemplate = (DataTemplate)Resources["DataTemplateA"];
}
else
{
MyListView.ItemTemplate = (DataTemplate)Resources["DataTemplateB"];
}
In the Code behind I can create the event handler but I cannot access the DisplayGrid to make it visible or to collapse it.
I would normally set visibility like this.
private void DisplayGridButton_Click(object sender, RoutedEventArgs e)
{
DisplayGrid.Visibility = Visibility.Visible;
}
private void HideGridButton_Click(object sender, RoutedEventArgs e)
{
DisplayGrid.Visibility = Visibility.Collapsed;
}
How do I access the DisplayGrid in the DataTemplate from the button click events?
Since the grid is defined in a template, you'll have to dig it out at runtime. (If you could reference it as "DisplayGrid" from code-behind, you wouldn't know which listview item it belonged to anyway.)
Implement click handlers something like this:
private void DisplayGridButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
StackPanel stackPanel = button?.Parent as StackPanel;
Grid grid = stackPanel?.Parent as Grid;
if (grid != null)
{
Grid displayGrid = FindVisualChild<Grid>(grid, "DisplayGrid");
if (displayGrid != null)
{
displayGrid.Visibility = Visibility.Visible;
}
}
}
private void HideGridButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
StackPanel stackPanel = button?.Parent as StackPanel;
Grid grid = stackPanel?.Parent as Grid;
if (grid != null)
{
grid.Visibility = Visibility.Collapsed;
}
}
(Fair warning: The way this code finds the appropriate parent to start from is a bit brittle; it might break if the template changes. Searching by name would be better, but I don't have anything handy right now.)
Here is the helper method that finds a named child in the visual tree:
public static T FindVisualChild<T>(
DependencyObject parent,
string name = null)
where T : DependencyObject
{
if (parent != null)
{
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
T candidate = child as T;
if (candidate != null)
{
if (name == null)
{
return candidate;
}
FrameworkElement element = candidate as FrameworkElement;
if (name == element?.Name)
{
return candidate;
}
}
T childOfChild = FindVisualChild<T>(child, name);
if (childOfChild != null)
{
return childOfChild;
}
}
}
return default(T);
}
(This method can also search by type only; just pass null as the name.)
Im implementing a UI in Windows 10 (UWP) with elements that can be moved using drag and drop from a menu area to a ScrollView area, it should also be possible to move the elements back to the menu area from the ScrollView. When a element is moved from the menu to the ScrollView the element is removed as child of the menu and added as a child to a child of the ScrollView.
But when I try to move the elements back they render behind the menu. I have played around with z index and the order the elements are in the XAML and tested to remove and re add the ScrollView at run-time to put it at top, but with no luck.
Seams like ScrollView children does not draw outside the view? Any suggestions on how to solve this?
Below is some sample code that illustrates the issue:
<Page x:Class="ScrollViewTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ScrollViewTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="Transparent"
Height="200"
Width="200">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1"
Canvas.ZIndex="1"
Background="Transparent">
<Canvas Background="Transparent"
Height="0"
Width="0"
VerticalAlignment="Top"
HorizontalAlignment="Left">
<Border Canvas.Left="-25"
Canvas.Top="100"
BorderThickness="2"
BorderBrush="Red"
Width="50"
Height="50"></Border>
</Canvas>
</Grid>
<ScrollViewer Grid.Column="0"
VerticalScrollMode="Enabled"
Canvas.ZIndex="2"
Background="Transparent">
<Canvas Background="Transparent"
Height="0"
Width="0"
VerticalAlignment="Top"
HorizontalAlignment="Left">
<Border Canvas.Left="75"
BorderThickness="2"
BorderBrush="Blue"
Width="50"
Height="50"></Border>
</Canvas>
</ScrollViewer>
</Grid>
And the result, I want the blue border to be shown on top of the grid
Seems like ScrollView children does not draw outside the view?
This is because the Content of Grid has a limited size which is exactly the size of itself, but the content of ScrollViewer has no limited size since it is scroll-able, not like a Grid, the child element of a ScrollViewer will always be rendered inside of it.
..., I want the blue border to be shown on top of the grid
To be honestly, I think it is not the right direction to use Canvas.ZIndex to implement the drag and drop gesture between different parent. A Canvas.ZIndex value is interpreted by the most immediate parent Canvas element from where the value is set. The value is used to explicitly define the draw order in cases where child elements overlap. In this case, your Grid and ScrollViewer have the same parent, but the Canvass have different parent.
Here I can give you a method to implement this function:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="rootGrid"
PointerPressed="rootGrid_PointerPressed"
PointerReleased="rootGrid_PointerReleased">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"></ColumnDefinition>
<ColumnDefinition Width="200"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Canvas x:Name="canvas" Grid.Column="1" Background="Wheat">
<Border BorderThickness="2" BorderBrush="Red" Width="50" Height="50" />
<Ellipse Width="50" Height="50" VerticalAlignment="Top" Fill="Red" />
</Canvas>
<ScrollViewer x:Name="scrollViewer" Grid.Column="0"
VerticalScrollMode="Enabled" VerticalScrollBarVisibility="Hidden"
Background="LightBlue">
<Canvas Width="100" x:Name="canvasInsideScrollViewer">
<Border BorderThickness="2" BorderBrush="Blue" Width="50" Height="50" VerticalAlignment="Bottom" />
</Canvas>
</ScrollViewer>
</Grid>
Code behind:
public Page20()
{
this.InitializeComponent();
this.Loaded += Page20_Loaded;
}
private void Page20_Loaded(object sender, RoutedEventArgs e)
{
gridRect = canvas.TransformToVisual(rootGrid).TransformBounds(new Rect(0.0, 0.0, canvas.ActualWidth, canvas.ActualHeight));
scrollViewerRect = scrollViewer.TransformToVisual(rootGrid).TransformBounds(new Rect(0.0, 0.0, scrollViewer.ActualWidth, scrollViewer.ActualHeight));
}
private Rect gridRect;
private Rect scrollViewerRect;
private FrameworkElement MoveElement;
private void rootGrid_PointerPressed(object sender, PointerRoutedEventArgs e)
{
var pointer = e.GetCurrentPoint(rootGrid);
if (gridRect.Left <= pointer.Position.X && pointer.Position.X <= gridRect.Right &&
gridRect.Top <= pointer.Position.Y && pointer.Position.Y <= gridRect.Bottom)
{
foreach (var childElement in canvas.Children)
{
var element = childElement as FrameworkElement;
Rect childBounds = element.TransformToVisual(rootGrid).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
if (childBounds.Left <= pointer.Position.X && pointer.Position.X <= childBounds.Right &&
childBounds.Top <= pointer.Position.Y && pointer.Position.Y <= childBounds.Bottom)
{
MoveElement = element;
canvas.Children.Remove(element);
}
}
}
else if (scrollViewerRect.Left <= pointer.Position.X && pointer.Position.X <= scrollViewerRect.Right &&
scrollViewerRect.Top <= pointer.Position.Y && pointer.Position.Y <= scrollViewerRect.Bottom)
{
foreach (var childElement in canvasInsideScrollViewer.Children)
{
var element = childElement as FrameworkElement;
Rect childBounds = element.TransformToVisual(rootGrid).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
if (childBounds.Left <= pointer.Position.X && pointer.Position.X <= childBounds.Right &&
childBounds.Top <= pointer.Position.Y && pointer.Position.Y <= childBounds.Bottom)
{
MoveElement = element;
canvasInsideScrollViewer.Children.Remove(element);
}
}
}
}
private void rootGrid_PointerReleased(object sender, PointerRoutedEventArgs e)
{
var pointer = e.GetCurrentPoint(rootGrid);
if (MoveElement != null)
{
if (gridRect.Left <= pointer.Position.X && pointer.Position.X <= gridRect.Right &&
gridRect.Top <= pointer.Position.Y && pointer.Position.Y <= gridRect.Bottom)
{
var canvasPointer = e.GetCurrentPoint(canvas);
canvas.Children.Add(MoveElement);
Canvas.SetLeft(MoveElement, canvasPointer.Position.X);
Canvas.SetTop(MoveElement, canvasPointer.Position.Y);
}
else if (scrollViewerRect.Left <= pointer.Position.X && pointer.Position.X <= scrollViewerRect.Right &&
scrollViewerRect.Top <= pointer.Position.Y && pointer.Position.Y <= scrollViewerRect.Bottom)
{
var scrollviewPointer = e.GetCurrentPoint(canvasInsideScrollViewer);
canvasInsideScrollViewer.Children.Add(MoveElement);
Canvas.SetLeft(MoveElement, scrollviewPointer.Position.X);
Canvas.SetTop(MoveElement, scrollviewPointer.Position.Y);
}
}
MoveElement = null;
}
As you can see, I changed the Grid in the second column to Canvas, so the element can be rendered in the absolute position as your mouse point. Here is the rendering image of my demo:
Here the most confusing part is that you want to translate UIElement between different parent controls, but if you put your Borders (which you want to drag and drop) also in the rootGrid, your Grid, ScrollViewer, Borders will have the same parent, then you can follow CustomBehaviorControl of XAMLBehaviorsSample to complete the drag-and-drop work.
I am new in MVVVM so please forgive me if it is stupid question. I am using this example http://www.codeproject.com/Articles/36848/WPF-Image-Pixel-Color-Picker-Element and included there library to get color of indicated by user pixel of image. it looks nice and dipsalys in rectangle selected color but i neeed to bind the selecteed value to viewmodel.
here is my xaml code:
<Window x:Class="MovieEditor.View.PixelSelector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrls="clr-namespace:ColorPickerControls;assembly=ColorPickerControls"
xmlns:local="clr-namespace:MovieEditor.MVVMCommon"
Title="FilterDesigner" Height="550" Width="550"
Icon="..\Resources\Images\icon.ico"
xmlns:VM="clr-namespace:MovieEditor.ViewModel">
<Window.DataContext>
<VM:PixelSelectorVM/>
</Window.DataContext>
<Window.Resources>
<local:ColorToBrushConverter x:Key="ColorToBrushConverter"/>
</Window.Resources>
<Grid Background="#FF191919" >
<DockPanel>
<Grid Margin="10,10,10,1">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto" MinHeight="38"/>
</Grid.RowDefinitions>
<Border BorderBrush="White" BorderThickness="5" Margin="0,39,0,11">
<ctrls:ImageColorPicker Binding.XmlNamespaceManager="{Binding p PixelSelectorVM.MyImageColorPicker, UpdateSourceTrigger=PropertyChanged}"
x:Name="image" Source ="{Binding Frame}" Margin="0,36,0,0"
/>
</Border>
<Border Width="77"
HorizontalAlignment="Center"
BorderBrush="White" BorderThickness="1" Margin="263,2,182,435">
<Rectangle Fill="{Binding ElementName=image, Path=SelectedColor,
Converter={StaticResource ColorToBrushConverter}}" RenderTransformOrigin="0.549,0.429" Margin="1"/>
</Border>
<Button Content="Save" Command="{Binding Save}" Margin="165,0,0,4" Grid.Row="1" HorizontalAlignment="Left" Width="60"/>
<Label Content="Selected pixel color:" HorizontalAlignment="Left" Height="18" Margin="140,11,0,0" VerticalAlignment="Top" Width="110"/>
<Button Content="Cancel" Command="{Binding Cancel}" Margin="0,1,165,4" HorizontalAlignment="Right" Width="60" RenderTransformOrigin="0.5,0.5" Grid.Row="1">
</Button>
</Grid>
</DockPanel>
</Grid>
</Window>
</code>
And here is my view model:
public class PixelSelectorVM : ViewModelBase
{
private BitmapImage frame;
public MainWindowVM parentMainWindowVM;
private ImageColorPicker imageColorPicker;
public ImageColorPicker MyImageColorPicker
{
get
{
return this.imageColorPicker;
}
set
{
this.imageColorPicker = value;
OnPropertyChanged("MyImageColorPicker");
}
}
public BitmapImage Frame
{
get
{
return this.frame;
}
set
{
this.frame = value;
OnPropertyChanged("Frame");
}
}
public PixelSelectorVM(BitmapImage image, MainWindowVM mainWindowVM)
{
this.frame = image;
this.parentMainWindowVM = mainWindowVM;
this.imageColorPicker = new ImageColorPicker();
this.imageColorPicker.Source = image;
}
public PixelSelectorVM() { }
public ICommand Save
{
get
{
return new RelayCommand(SaveExecute);
}
}
public ICommand Cancel
{
get
{
return new RelayCommand(CancelExecute);
}
}
private void SaveExecute()
{
}
private void CancelExecute()
{
}
}
Please suggest me solution how can i pass the selected color to view model
You should be able to bind ImageColorPicker's SelectedColor to ViewModel's Property.
So in XAML add the binding:
SelectedColor="{Binding MySelectedColor, Mode=TwoWay}"
And in VM add the MySelectedColor property:
private Color selectedColor;
public Color MySelectedColor
{
get
{
return this.selectedColor;
}
set
{
this.selectedColor = value;
OnPropertyChanged("MySelectedColor");
}
}
When control's SelectedColor changes, it should automatically update the MySelectedColor in your VM.
I'm looking to show a dynamic number of buttons in a horizontal way, so that they always fill up the space horizontally no matter how many items.
For example, when there are two button
__________________________________
| other controls |
| |
|________________________________|
| Button 1 | Button 2 | Button 3 |
----------------------------------
and button 2 gets hidden(collapsed), this should become
__________________________________
| other controls |
| |
|________________________________|
| Button 1 | Button 3 |
----------------------------------
Is this possible with Winrt/WP 8.1 xaml?
I would work with a Grid and set the column width to zero in order to hide it. Since all other columns have star values they should stretch accordingly. If everything fails you can recalculate the star values manually since you know the number of visible buttons.
Sample:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="Foo" Margin="0,0,0,0" HorizontalAlignment="Stretch" />
<Button Grid.Column="1" Content="Foo" Margin="0,0,0,0" HorizontalAlignment="Stretch" />
<Button Grid.Column="2" Content="Foo" Margin="0,0,0,0" HorizontalAlignment="Stretch" />
</Grid>
Set the ColumnDefinition of one column to zero and the button is hidden and the other columns adjust accordingly.
You can always provide your own custom layout logic by deriving from Panel. Here's what I came up with:
StretchPanel.cs
class StretchPanel : Panel
{
#region Properties
public bool EqualWidths
{
get { return (bool)GetValue(EqualWidthsProperty); }
set { SetValue(EqualWidthsProperty, value); }
}
public static readonly DependencyProperty EqualWidthsProperty =
DependencyProperty.Register("EqualWidths", typeof(bool), typeof(StretchPanel), new PropertyMetadata(false, onEqualWidthsChanged));
#endregion
static void onEqualWidthsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var panel = (StretchPanel)d;
panel.InvalidateMeasure();
panel.InvalidateArrange();
}
protected override Size MeasureOverride(Size availableSize)
{
var renderedChildren = Children.Where(c => c.Visibility == Visibility.Visible);
var count = renderedChildren.Count();
Size childAvailableSize = availableSize;
if (EqualWidths)
childAvailableSize = new Size(availableSize.Width / count, availableSize.Height);
foreach (var child in renderedChildren)
child.Measure(childAvailableSize);
var totalHeight = renderedChildren.Max(c => c.DesiredSize.Height);
return new Size(availableSize.Width, totalHeight);
}
protected override Size ArrangeOverride(Size finalSize)
{
var renderedChildren = Children.Where(c => c.Visibility == Visibility.Visible);
var count = renderedChildren.Count();
var equalWidth = finalSize.Width / count;
var totalWidth = renderedChildren.Sum(c => c.DesiredSize.Width);
var totalHeight = renderedChildren.Max(c => c.DesiredSize.Height);
var x = 0.0;
foreach (var child in renderedChildren)
{
var r = new Rect();
r.X = x;
r.Y = 0;
r.Width = EqualWidths ? equalWidth : child.DesiredSize.Width / totalWidth * finalSize.Width;
r.Height = child.DesiredSize.Height;
child.Arrange(r);
x += r.Width;
}
return new Size(finalSize.Width, totalHeight);
}
}
You can use it like so:
<Page
x:Class="App19.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App19"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<Style TargetType="Button">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="MinWidth" Value="0" />
</Style>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="16" />
<Setter Property="Foreground" Value="Yellow" />
<Setter Property="Margin" Value="0,10,0,0" />
</Style>
</Page.Resources>
<StackPanel>
<TextBlock>Different widths</TextBlock>
<local:StretchPanel EqualWidths="False">
<Button>a</Button>
<Button>big</Button>
<Button>purple</Button>
<Button>dishwasher</Button>
</local:StretchPanel>
<TextBlock>Equal widths</TextBlock>
<local:StretchPanel EqualWidths="True">
<Button>a</Button>
<Button>big</Button>
<Button>purple</Button>
<Button>dishwasher</Button>
</local:StretchPanel>
<TextBlock>Different widths, one child hidden</TextBlock>
<local:StretchPanel EqualWidths="False">
<Button>a</Button>
<Button>big</Button>
<Button Visibility="Collapsed">purple</Button>
<Button>dishwasher</Button>
</local:StretchPanel>
<TextBlock>Equal widths, one child hidden</TextBlock>
<local:StretchPanel EqualWidths="True">
<Button>a</Button>
<Button>big</Button>
<Button Visibility="Collapsed">purple</Button>
<Button>dishwasher</Button>
</local:StretchPanel>
</StackPanel>
</Page>
And a screenshot:
I'm trying to create a similar experience as in the ScrollViewerSample from the Windows 8 SDK samples to be able to snap to the items inside a ScrollViewer when scrolling left and right. The implementation from the sample (which works) is like this:
<ScrollViewer x:Name="scrollViewer" Width="480" Height="270"
HorizontalAlignment="Left" VerticalAlignment="Top"
VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto"
ZoomMode="Disabled" HorizontalSnapPointsType="Mandatory">
<StackPanel Orientation="Horizontal">
<Image Width="480" Height="270" AutomationProperties.Name="Image of a cliff" Source="images/cliff.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of Grapes" Source="images/grapes.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of Mount Rainier" Source="images/Rainier.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of a sunset" Source="images/sunset.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of a valley" Source="images/valley.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
</ScrollViewer>
The only difference with my desired implementation is that I don't want a StackPanel with items inside, but something I can bind to. I am trying to accomplish this with an ItemsControl, but for some reason the Snap behavior does not kick in:
<ScrollViewer x:Name="scrollViewer" Width="480" Height="270"
HorizontalAlignment="Left" VerticalAlignment="Top"
VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto"
ZoomMode="Disabled" HorizontalSnapPointsType="Mandatory">
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<Image Width="480" Height="270" AutomationProperties.Name="Image of a cliff" Source="images/cliff.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of Grapes" Source="images/grapes.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of Mount Rainier" Source="images/Rainier.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of a sunset" Source="images/sunset.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Image Width="480" Height="270" AutomationProperties.Name="Image of a valley" Source="images/valley.jpg" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</ItemsControl>
</ScrollViewer>
Suggestions would be greatly appreciated!
Thanks to Denis, I ended up using the following Style on the ItemsControl and removed the ScrollViewer and inline ItemsPanelTemplate altogether:
<Style x:Key="ItemsControlStyle" TargetType="ItemsControl">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer Style="{StaticResource HorizontalScrollViewerStyle}" HorizontalSnapPointsType="Mandatory">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Getting snap points to work for bound collections can be tricky. For snap points to work immediate child of ScrollViewer should implement IScrollSnapPointsInfo interface. ItemsControl doesn't implement IScrollSnapPointsInfo and consequently you wouldn't see snapping behaviour.
To work around this issue you got couple options:
Create custom class derived from ItemsControl and implement IScrollSnapPointsInfo interface.
Create custom style for items control and set HorizontalSnapPointsType property on ScrollViewer inside the style.
I've implemented former approach and can confirm that it works, but in your case custom style could be a better choice.
Ok, here is the simplest (and standalone) example for horizontal ListView with binded items and correctly working snapping (see comments in following code).
xaml:
<ListView x:Name="YourListView"
ItemsSource="{x:Bind Path=Items}"
Loaded="YourListView_OnLoaded">
<!--Set items panel to horizontal-->
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<!--Some item template-->
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
background code:
private void YourListView_OnLoaded(object sender, RoutedEventArgs e)
{
//get ListView
var yourList = sender as ListView;
//*** yourList style-based changes ***
//see Style here https://msdn.microsoft.com/en-us/library/windows/apps/mt299137.aspx
//** Change orientation of scrollviewer (name in the Style "ScrollViewer") **
//1. get scrollviewer (child element of yourList)
var sv = GetFirstChildDependencyObjectOfType<ScrollViewer>(yourList);
//2. enable ScrollViewer horizontal scrolling
sv.HorizontalScrollMode =ScrollMode.Auto;
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
sv.IsHorizontalRailEnabled = true;
//3. disable ScrollViewer vertical scrolling
sv.VerticalScrollMode = ScrollMode.Disabled;
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
sv.IsVerticalRailEnabled = false;
// //no we have horizontally scrolling ListView
//** Enable snapping **
sv.HorizontalSnapPointsType = SnapPointsType.MandatorySingle; //or you can use SnapPointsType.Mandatory
sv.HorizontalSnapPointsAlignment = SnapPointsAlignment.Near; //example works only for Near case, for other there should be some changes
// //no we have horizontally scrolling ListView with snapping and "scroll last item into view" bug (about bug see here http://stackoverflow.com/questions/11084493/snapping-scrollviewer-in-windows-8-metro-in-wide-screens-not-snapping-to-the-las)
//** fix "scroll last item into view" bug **
//1. Get items presenter (child element of yourList)
var ip = GetFirstChildDependencyObjectOfType<ItemsPresenter>(yourList);
// or var ip = GetFirstChildDependencyObjectOfType<ItemsPresenter>(sv); //also will work here
//2. Subscribe to its SizeChanged event
ip.SizeChanged += ip_SizeChanged;
//3. see the continuation in: private void ip_SizeChanged(object sender, SizeChangedEventArgs e)
}
public static T GetFirstChildDependencyObjectOfType<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj is T) return depObj as T;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = GetFirstChildDependencyObjectOfType<T>(child);
if (result != null) return result;
}
return null;
}
private void ip_SizeChanged(object sender, SizeChangedEventArgs e)
{
//3.0 if rev size is same as new - do nothing
//here should be one more condition added by && but it is a little bit complicated and rare, so it is omitted.
//The condition is: yourList.Items.Last() must be equal to (yourList.Items.Last() used on previous call of ip_SizeChanged)
if (e.PreviousSize.Equals(e.NewSize)) return;
//3.1 get sender as our ItemsPresenter
var ip = sender as ItemsPresenter;
//3.2 get the ItemsPresenter parent to get "viewable" width of ItemsPresenter that is ActualWidth of the Scrollviewer (it is scrollviewer actually, but we need just its ActualWidth so - as FrameworkElement is used)
var sv = ip.Parent as FrameworkElement;
//3.3 get parent ListView to be able to get elements Containers
var yourList = GetParent<ListView>(ip);
//3.4 get last item ActualWidth
var lastItem = yourList.Items.Last();
var lastItemContainerObject = yourList.ContainerFromItem(lastItem);
var lastItemContainer = lastItemContainerObject as FrameworkElement;
if (lastItemContainer == null)
{
//NO lastItemContainer YET, wait for next call
return;
}
var lastItemWidth = lastItemContainer.ActualWidth;
//3.5 get margin fix value
var rightMarginFixValue = sv.ActualWidth - lastItemWidth;
//3.6. fix "scroll last item into view" bug
ip.Margin = new Thickness(ip.Margin.Left,
ip.Margin.Top,
ip.Margin.Right + rightMarginFixValue, //APPLY FIX
ip.Margin.Bottom);
}
public static T GetParent<T>(DependencyObject reference) where T : class
{
var depObj = VisualTreeHelper.GetParent(reference);
if (depObj == null) return (T)null;
while (true)
{
var depClass = depObj as T;
if (depClass != null) return depClass;
depObj = VisualTreeHelper.GetParent(depObj);
if (depObj == null) return (T)null;
}
}
About this example.
Most of checks and errors handling is omitted.
If you override ListView Style/Template, VisualTree search parts must be changed accordingly
I'd rather create inherited from ListView control with this logic, than use provided example as-is in real code.
Same code works for Vertical case (or both) with small changes.
Mentioned snapping bug - ScrollViewer bug of handling SnapPointsType.MandatorySingle and SnapPointsType.Mandatory cases. It appears for items with not-fixed sizes
.