Showing posts with label xaml. Show all posts
Showing posts with label xaml. Show all posts

Friday, May 25, 2018

A ListView column with an image in its data template is not visible

Leave a Comment

I have the following three data templates:

<HierarchicalDataTemplate DataType="{x:Type models:DirOrFileItem}" ItemsSource="{Binding Children}">     <StackPanel Orientation="Horizontal">         <Image Source="../Images/Folder.png"  Stretch="Uniform" Height="20"></Image>         <TextBlock Text="{Binding Name}" ToolTip="{Binding RelativePath}"></TextBlock>     </StackPanel> </HierarchicalDataTemplate>  <DataTemplate x:Key="SelectColTemplate">     <CheckBox IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}" /> </DataTemplate> <DataTemplate x:Key="IconTemplate">     <Image Source="{Binding ImageData}" Stretch="Uniform" Height="20" /> </DataTemplate> 

I set the ImageData property on the row viewmodel as follows:

item.ImageData = ImageHelper.LoadImage(AppConstants.FileRsourcePath); 

where LoadImage is:

public static BitmapImage LoadImage(string filename) {     return new BitmapImage(new Uri("pack://application:,,,/" + filename)); } 

I know it loads the image correctly because when I examine the ImageData property after setting it, it has properties that are correct for the image that was loaded.

The HierarchicalDataTemplate is for a TreeView, and the image folder.png appears as and where expected. Then I have the following ListView columns:

<GridViewColumn CellTemplate="{StaticResource SelectColTemplate}" Width="30" /> <GridViewColumn CellTemplate="{StaticResource IconTemplate}" Width="30" /> <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" Width="360" /> 

I am displaying a list of files and folders, and would like an image to highlight which is which.

The CheckBox appears where it should, in the first column, and the third column in the markup appears as the second column on screen, as if the column with the image template, IconTemplate, does not exist.

Both images are where they should be, in the same Images folder, so why is my "image column" not appearing as the second column as I expect?

BONUS QUESTION: If, as @Clemens suggests below in his comment, I set the Build Action of the images to Resource and and load them by Resource File Pack URIs, how would I do so in XAML?

2 Answers

Answers 1

Just set Build Action in your image properties to Resource and set full path to your image. It will appear. http://prntscr.com/jjw4z3

Answers 2

As long you don't need to destroy it....you don't have to load the image, just give the URI in the binding ==> ImageData = new Uri("pack://application:,,,/" + filename)); and the Image control will load it

btw, your viewmodel must not have GUI related element like bitmap image bye.

Read More

Wednesday, April 11, 2018

Half of an image above other image in xamarin forms

Leave a Comment

I am working with xamarin forms And I need to create a layout with two objects positionated like that:

enter image description here

half of one(circle) above the other object(square)

I have searched and it seem I need to use relative layout... I tried to do that setting the both objects in the same grid (row and line 0), and then, using constraintX to set the second in the same Y with factor 0 and a negative constant...But it didn't work. The a deleted the lines and can't show here, unfortunately...the only thing that happend in this is: the both was in the same position in y, but I could do like the image above... Can someone help me with an example, idea or anything? thank you very much!

My code now - the rodape image is the square and the reload is the circle I now the fact that the reload is under the square is wrong, but, for now, it is pretend the visual...an it gives me a result close that I want...but not exactly

<!--Rodapé Grid--> <RelativeLayout HorizontalOptions="FillAndExpand"                  VerticalOptions="EndAndExpand"                  BackgroundColor="Black">     <Grid BackgroundColor="Red"            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,                                                                  Property=Width,                                                                  Factor=1,                                                                  Constant=0}">         <Grid.RowDefinitions>             <RowDefinition Height="*"/>         </Grid.RowDefinitions>          <Image Source="rodape.png"                 Aspect="Fill"                HorizontalOptions="FillAndExpand"                Grid.Row="0"                Grid.Column="0">             <Image.GestureRecognizers>                 <TapGestureRecognizer Tapped="FranqueadoOnTapGestureRecognizerTapped"/>             </Image.GestureRecognizers>         </Image>         <!--Escrito Rodapé-->         <StackLayout Orientation="Vertical"                      VerticalOptions="End"                      HorizontalOptions="FillAndExpand"                      Grid.Row="0"                      Spacing="0"                      Grid.Column="0">             <Image Source="reloadicon.png"/>             <StackLayout Orientation="Horizontal"                           HorizontalOptions="Center">                 <local:MyLabel NamedFontSize="Medium"                                 FontSizeFactor="0.7"                                 Text="Seja um Franqueado:"                                TextColor="White"                                FontAttributes="Bold"                                Style="{StaticResource labelsfont}"/>                 <local:MyLabel NamedFontSize="Medium"                                 FontSizeFactor="0.7" Text="montanaexpress.com"                                Style="{StaticResource labelsfont}"                                TextColor="{StaticResource laranjacolor}"/>                           </StackLayout>         </StackLayout>     </Grid> </RelativeLayout> 

1 Answers

Answers 1

Try something like this, I think it's simpler:

<Grid>     <BoxView Grid.Column="0" Grid.Row="1"              Color="Red"              HeightRequest="20"              HorizontalOptions="FillAndExpand"/>     <Frame Grid.Column="0" Grid.Row="0" Grid.RowSpan="2"            BackgroundColor="Yellow"            HorizontalOptions="CenterAndExpand"            VerticalOptions="CenterAndExpand"            WidthRequest="40"            HeightRequest="40"            CornerRadius="40"            Margin="0,5,0,10"/> </Grid> 

What you'll get: enter image description here

EDIT:

As you've required at comments, using your images you should do something like this:

<Grid>        <Image Grid.Row="1" Grid.Column="0"            Source="rodape.png"             Aspect="Fill"            HorizontalOptions="FillAndExpand">         <Image.GestureRecognizers>             <TapGestureRecognizer Tapped="FranqueadoOnTapGestureRecognizerTapped"/>         </Image.GestureRecognizers>     </Image>                    <Image Grid.Column="0" Grid.Row="0" Grid.RowSpan="2"            Source="reloadicon.png"            HorizontalOptions="CenterAndExpand"            VerticalOptions="Center"/> </Grid> 

Note: I'm not able to figure out how the labels and the image should be displayed in your layout. You have to add it manually

Read More

Sunday, March 25, 2018

Binding to a nested property inside ControlTemplate

Leave a Comment

The aim is to build up a resource dictionary of icon path geometries for my custom button template.

What works so far:

ResourceDictionary:

<Geometry x:Key="ArrowDown">     M0,10 M10,0 M5,1 L5,7 4.2,7 5,8 5.8,7 5,7 </Geometry> <Geometry x:Key="ArrowUp">     M0,0 M10,10 M5,9 L5,3 4.2,3 5,2 5.8,3 5,3 </Geometry> 

Attached property for the Path:

public static Geometry GetIconPath(UIElement element) {     return (Geometry)element.GetValue(IconPathProperty); }  public static void SetIconPath(UIElement element, Geometry value) {     element.SetValue(PIconPathProperty, value); }  public static readonly DependencyProperty IconPathProperty =     DependencyProperty.RegisterAttached("IconPath", typeof(Geometry), typeof(Attached)); 

Template:

<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">     <Viewbox>         <Path Name="Icon" Stroke="Black" StrokeThickness="1" Stretch="Uniform"               Data="{Binding (local:Attached.IconPath), RelativeSource={RelativeSource TemplatedParent}}"/>     </Viewbox>     <ControlTemplate.Triggers>         <Trigger Property="IsEnabled" Value="False">             <Setter Property="Stroke" TargetName="Icon" Value="Gray"/>             <Setter TargetName="Icon" Property="Effect">                 <Setter.Value>                     <DropShadowEffect ShadowDepth="0.2" Color="Black" Direction="125"/>                 </Setter.Value>             </Setter>         </Trigger>     </ControlTemplate.Triggers> </ControlTemplate> 

The button:

<Button local:Attached.IconPath="{StaticResource ArrowDown}"/> 

This works fine, but I now have an added layer of complexity: some of the icons need to be Filled and others don't. And I'd like to have this information in the ResourceDictionary with the GeometryData.

One solution would be to store the whole Path in the ResourceDictionary, but as you can see in the ControlTemplate, I need to be able to access the Path to trigger the DropShadowEffect.

So the alternative solution I'm attempting is to use a POCO to store both elements in:

public class IconData {     public bool Fill { get; set; }     public Geometry Geometry { get; set; } } 

So the ResourceDictionary now contains:

<local:IconData x:Key="ArrowUp" Fill="True" Geometry="     M0,0 M10,10 M5,9 L5,3 4.2,3 5,2 5.8,3 5,3"/> 

With the appropriate attached Property, the ControlTemplate becomes:

<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">     <Viewbox>         <Path Name="Icon" Stroke="Black" StrokeThickness="1" Stretch="Uniform"               Data="{Binding (local:Attached.IconData.Geometry), RelativeSource={RelativeSource TemplatedParent}}"/>     </Viewbox>     <ControlTemplate.Triggers>         <Trigger Property="local:Attached.IconData.Fill" Value="True">             <Setter Property="Fill" TargetName="Icon" Value="#00000000"/>         </Trigger>         <Trigger Property="IsEnabled" Value="False">             <Setter Property="Stroke" TargetName="Icon" Value="Gray"/>             <Setter TargetName="Icon" Property="Effect">                 <Setter.Value>                     <DropShadowEffect ShadowDepth="0.2" Color="Black" Direction="125"/>                 </Setter.Value>             </Setter>         </Trigger>     </ControlTemplate.Triggers> </ControlTemplate> 

And unfortunately, both references to IconData here say Nested types are not supported: Attached.IconData.

I'm open to a solution to my implementation, or any workaround or different solution.

1 Answers

Answers 1

<Path Name="Icon" Stroke="Black" StrokeThickness="1" Stretch="Uniform"       Data="{Binding (local:Attached.IconData.Geometry), RelativeSource={RelativeSource TemplatedParent}}"/> 

Here (local:Attached.IconData.Geometry) means a nested type. To get a property of Attached.IconData object one should use following binding path:

<Path Name="Icon" Stroke="Black" StrokeThickness="1" Stretch="Uniform"       Data="{Binding (local:Attached.IconData).Geometry, RelativeSource={RelativeSource TemplatedParent}}"/> 

Also be sure to change the attached property type from Geometry to IconData in Attached type.

IconData class shouldn't be nested to any type, because it's exactly what is said to be not supported (just put in in the same namespace as other used types).

After these modifications your code started working for me.

Here's main window XAML:

<Window x:Class="WpfApplication1.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:local="clr-namespace:WpfApplication1"         Title="MainWindow" Height="250" Width="260">     <Window.Resources>         <ResourceDictionary>             <local:IconData x:Key="ArrowUp" Fill="False" Geometry="M0,0 M10,10 M4.8,9 4.8,3 4.2,3 5,2 5.8,3 5.2,3 5.2,9 Z"/>             <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">                 <Viewbox>                     <Path Name="Icon" Stretch="Uniform"                           Data="{Binding (local:Attached.IconPath).Geometry, RelativeSource={RelativeSource TemplatedParent}}">                         <Path.Style>                             <Style TargetType="Path">                                 <Style.Triggers>                                     <DataTrigger Binding="{Binding (local:Attached.IconPath).Fill, RelativeSource={RelativeSource TemplatedParent}}"                                                      Value="True">                                         <Setter Property="Fill" Value="Black" />                                     </DataTrigger>                                     <DataTrigger Binding="{Binding (local:Attached.IconPath).Fill, RelativeSource={RelativeSource TemplatedParent}}"                                                      Value="False">                                         <Setter Property="Stroke" Value="Black" />                                         <Setter Property="StrokeThickness" Value="0.2" />                                     </DataTrigger>                                 </Style.Triggers>                             </Style>                         </Path.Style>                     </Path>                 </Viewbox>             </ControlTemplate>          </ResourceDictionary>     </Window.Resources>      <Button local:Attached.IconPath="{StaticResource ArrowUp}" Template="{StaticResource ButtonTemplate}" /> </Window> 

Note, that I've amended the path geometry on M0,0 M10,10 M4.8,9 4.8,3 4.2,3 5,2 5.8,3 5.2,3 5.2,9 Z to make it closed and thus suitable to fill.

Here are screenshots for cases <local:IconData Fill="False" ... /> and <local:IconData Fill="True" ... />:

A screenshot for case Fill=False A screenshot for case Fill=True

Read More

Monday, March 19, 2018

Preserve theme style of control while modifying the control template

Leave a Comment

I'm trying to add bind some commands to Slider.Thumb and this is how I currently do it:

<Style x:Key="BasicSliderStyle" TargetType="{x:Type customControls:ThumbDragSlider}" BasedOn="{StaticResource {x:Type Slider}}">     <Setter Property="Template">         <Setter.Value>             <ControlTemplate TargetType="{x:Type Slider}">                 <Grid>                     <Track x:Name="PART_Track">                         <Track.Thumb>                             <Thumb x:Name="Thumb">                                 <i:Interaction.Triggers>                                     <i:EventTrigger EventName="MouseEnter">                                         <command:EventToCommand Command="{Binding PositionSliderThumbMouseEnterCommand}" PassEventArgsToCommand="True"/>                                     </i:EventTrigger>                                     <i:EventTrigger EventName="DragDelta">                                         <command:EventToCommand Command="{Binding PositionThumbDragDeltaCommand}" CommandParameter="{Binding ElementName=sMovieSkipSlider}"/>                                     </i:EventTrigger>                                 </i:Interaction.Triggers>                             </Thumb>                         </Track.Thumb>                     </Track>                 </Grid>             </ControlTemplate>         </Setter.Value>     </Setter> </Style> 

The problem is that I also have a theme applied to my controls and if I use this style the style and effects from it are removed as well, is there a way to keep the current application theme style on a control while also being able to add event triggers and attach commands as show above?

P.S - Since this is a custom control that derives from Slider, this is how I set the default theme style for the slider to it

Style="{StaticResource {x:Type Slider}}" 

2 Answers

Answers 1

You can only use Triggers in the Style and not in the Template, if you want to keep the same theme for that control. That means that it is not possible in your case. What you can do is copy the entire Style of your theme and specify the trigger there.

Answers 2

You can extend your custom style. Instead of:

BasedOn="{StaticResource {x:Type Slider}}" 

do:

BasedOn="{StaticResource MyCustomSlider}" 
Read More

Tuesday, February 20, 2018

Xamarin.Forms: How to properly use <OnPlatform> to pick which control to use in my TableSection?

Leave a Comment

I have a TableView with few sections. In my TableSection I want to display different controls depending on the platform. I want to use the usual TextCell for iOS and a custom ViewCell for Android. I have tried the following code:

<TableSection Title="Activity">    <OnPlatform x:TypeArguments="View">       <On Platform="iOS">          <TextCell x:Name="btnCountIOS" Text="Count" Height="50" />          <TextCell x:Name="cardHistory" Text="History" StyleId="disclosure" Tapped="openHistoryPage" Height="50"/>       </On>       <On Platform="Android">          <local:MyViewCell NoTap="true" Height="50">             <Grid VerticalOptions="CenterAndExpand" Padding="20, 0">                <Label Style="{DynamicResource ListItemTextStyle}" HorizontalOptions="StartAndExpand" VerticalOptions="Center" Text="Today" />                <Label Style="{DynamicResource ListItemTextStyle}" TextColor="Gray" HorizontalOptions="End" x:Name="btnCountDroid" />             </Grid>          </local:MyViewCell>          <local:MyViewCell>             <!-- more code here -->          </local:MyViewCell>       </On>    </OnPlatform> </TableSection> 

The above code does not work. It gives me an error: Object reference not set to an instance of an object.

Am I missing something? Should I be using a different x:TypeArguments?

Edit:

Edited to incorporate @Fahadsk answer and now getting the error: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. Anyone knows why I'm getting this?

1 Answers

Answers 1

OnPlatform is obsolete as of version 2.3.4.

Use following syntax in your code

<OnPlatform x:TypeArguments="Thickness">      <On Platform="Android" Value="0, 0, 0, 0"/>      <On Platform="iOS" Value="0, 20, 0, 0"/> </OnPlatform> 

For more info on this and this pull request, also check out this blog

Read More

Tuesday, February 13, 2018

Adding an “Android.Views.ViewGroup” to a Xamarin XAML page

Leave a Comment

I need some help with adding an Android.Views.ViewGroup to a XAML page.

I have a Xamarin project with a solution structure that looks like this:

  • App1
    • /ViewModels
      • /MyPageViewModel.cs
    • /Views
      • /MyPageView.xaml
        • /MyPageView.xaml.cs
  • App1.Android
    • /MainActivity.cs
    • /MainApplication.cs
  • App1.iOS
  • MyAndroidBindingProject
    • /Jars
      • /customViewGroup.aar

Note the customViewGroup.aar that I've added to the solution using a Xamarin Android Binding Library.

The AAR file contains an Android.Views.ViewGroup class that I'd like to show on MyPage.xaml but I have no clue how to do it. I can't seem to find a guide or code sample that fits this exact use case (nor can I find one that involves adding a simple Android.Views.View to a Xamarin XAML page).

I've found examples of adding an Android.Views.ViewGroup to a native Android application (using Java and XML) but nothing that shows how to add it to a Xamarin XAML page.

Please help!


I'm including some source code so you can see what I've tried:

MyPage.xaml

<ContentPage      xmlns="http://xamarin.com/schemas/2014/forms"     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"     x:Class="App1.Views.MyPage"     xmlns:vm="clr-namespace:App1.ViewModels;"     xmlns:androidWidget="clr-namespace:Com.CustomAAR;assembly=Com.CustomAAR;targetPlatform=Android"     xmlns:formsAndroid="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.Platform.Android;targetPlatform=Android"     Title="{Binding Title}">     <ContentPage.Content>         <ContentView x:Name="contentViewParent">             <androidWidget:MyCustomViewGroup x:Arguments="{x:Static formsandroid:Forms.Context}">              </androidWidget:MyCustomViewGroup>         </ContentView>         <!--<ContentView              IsVisible="True"             IsEnabled="True"             BindingContext="{Binding MyCustomViewGroup}">         </ContentView>-->     </ContentPage.Content> </ContentPage> 

MyPage.xaml.cs

public partial class MyPage : ContentPage {     MyCustomViewGroupModel viewModel;      public MyPage()     {         InitializeComponent ();     }      public MyPage(MyCustomViewGroupModel viewModel)     {         InitializeComponent();  #if __ANDROID__         NativeViewWrapper wrapper = (NativeViewWrapper)contentViewParent.Content;         MyCustomViewGroup myCustomViewGroup = (MyCustomViewGroup)wrapper.NativeView;          //myCustomViewGroup = new MyCustomViewGroup(Android.App.Application.Context);          myCustomViewGroup.SomeAction(""); #endif          BindingContext = this.viewModel = viewModel;     } } 

1 Answers

Answers 1

To include native controls in your Xamarin.Forms page you will need to create a custom control and platform renderer. See the official documentation for full walkthrough.

In a gist, you first you declare a new control in your shared project:

public class MyCustomViewControl : View {  } 

Now in the Android project you create a custom renderer, that will use your custom Android view to display natively:

public class MyCustomViewRenderer : ViewRenderer<MyCustomViewControl, MyCustomViewGroup> {     MyCustomViewGroup viewGroup;      public MyCustomViewRenderer(Context context) : base(context)     {     }      protected override void OnElementChanged(ElementChangedEventArgs<MyCustomViewControl> e)     {         base.OnElementChanged(e);          if (Control == null)         {             viewGroup= new MyCustomViewGroup(Context);             SetNativeControl(viewGroup);         }     } } 

You will also use the renderer to setup events, etc. on the native side.

The renderer is recognized and registered by Xamarin.Forms thanks to the attribute, that can be in the same file as the Renderer, above the namespace:

[assembly: ExportRenderer (typeof(MyCustomViewControl), typeof(MyCustomViewRenderer))] 
Read More

Wednesday, January 17, 2018

NavigationPage Wrapping causing bug in status bar

Leave a Comment

I'm experiencing a weird bug when I try to add Navigation to my CropsListPage

<?xml version="1.0" encoding="utf-8" ?> <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"        xmlns:local="clr-namespace:Chronocrops.Views"        x:Class="Balloney.Views.MainPage">     <NavigationPage Icon="carrot.png">     <x:Arguments>         <local:CropListPage/>     </x:Arguments>    </NavigationPage>     <ContentPage Icon="search.png"></ContentPage>   </TabbedPage> 

And then it results in..

enter image description here

If I don't try to envelop it in a NavigationPage, it stays normal

enter image description here

Any idea what's causing this behaviour ? Before trying to hammer my way outta this and hardcoding the size of the status bar in Android, I'm looking for a way to understand the problem and prevent it. Thanks

MainPage.xaml working now

<?xml version="1.0" encoding="utf-8" ?> <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"            xmlns:local="clr-namespace:Chronocrops.Views"            x:Class="Balloney.Views.MainPage">    <local:CropListPage Icon="carrot.png"/>   <ContentPage Icon="search.png"></ContentPage>  </TabbedPage> 

And the CropList xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"          xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"          x:Class="Balloney.Views.CropListPage"> <ListView ItemsSource="{Binding CropsList}" ItemTapped="OnCropTapped">     <ListView.ItemTemplate>         <DataTemplate>             <ViewCell>                 <StackLayout Orientation="Horizontal">                     <Image Source="{Binding ImageUrl}" VerticalOptions="Fill" WidthRequest="50"/>                     <StackLayout HorizontalOptions="StartAndExpand">                         <Label Text="{Binding Specie.Name}"/>                         <Label Text="{Binding HarvestDate}" FontSize="Micro" TextColor="Black"/>                     </StackLayout>                     <Label Text="{Binding Location}" FontSize="Micro" TextColor="Chocolate" />                 </StackLayout>             </ViewCell>         </DataTemplate>     </ListView.ItemTemplate> </ListView> </ContentPage> 

EDIT: The error seems to be related to the ListView I have inside CropListPage because there's no bug when I switch to the Search icon Page.

enter image description here

2 Answers

Answers 1

The extra space in your first image is the result of the NavigationPage by default showing the Navigation bar, which can be hidden.

Here's an example of how to hide it.

Answers 2

Is may be because you have wrapped crop list page in a navigation page so when that is selected you get the nav bar space above.

If you select the second tab, does the space disappear?

If you add a title to crop page does it appear in the large green space?

<?xml version="1.0" encoding="utf-8" ?> <TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"        xmlns:local="clr-namespace:Chronocrops.Views"        x:Class="Chronocrops.Views.MainPage">     <NavigationPage Icon="carrot.png" Title="Crop List">     <x:Arguments>         <local:CropListPage/>     </x:Arguments>    </NavigationPage>     <ContentPage Icon="search.png"></ContentPage>   </TabbedPage> 
Read More

Thursday, December 7, 2017

Using Custom Resource in DevExpress WPF Theme

Leave a Comment

Objective:

I have a WPF project which shall be themed using DevExpress Themes. There is a Login-UserControl that shall have a themable background image.

Implementation

I made a custom Theme. In that theme I have a Folder "CustomResources" in which there is an Image, let's call it "Background.png" and a "Brushes.xaml" that defines an ImageBrush like this:

<ResourceDictionary ...>     <ImageBrush x:Key="{CustomThemeKeyAssembly:CustomThemeResourcesThemeKey ResourceKey=LoginBackgroundImageBrush, ThemeName=CustomTheme}" ImageSource="Background.png" /> </ResourceDictionary> 

Accordingly, I have a shared Assembly CustomThemeKeyAssembly that derives a Custom ResourceThemeKey.

In the Project, I register and set the Theme using ApplicationThemeHelper

var theme = new Theme("CustomTheme") {     AssemblyName = "DevExpress.Xpf.Themes.CustomTheme.v17.2" }; Theme.RegisterTheme(theme);  ApplicationThemeHelper.ApplicationThemeName = "CustomTheme"; 

and I reference the Resource through

Background="{dxci:ThemeResource ThemeKey={CustomThemeKeyAssembly:CustomThemeResourcesThemeKey ResourceKey=LoginBackgroundImageBrush}}" 

As advised by DevExpress Knowledgebase / Support.

Problem

The Resource is only found and displayed, if I add a Merged Resource Dictionary like this:

ResourceDictionary loginBackgroundDictionary = new ResourceDictionary {     Source = new Uri($"pack://application:,,,/{MyProject.Properties.Settings.Default.ThemeAssembly};Component/CustomResources/Brushes.xaml", UriKind.Absolute) };  //Add LoginBackgroundImageBrush Dictionary Resources.MergedDictionaries.Add(loginBackgroundDictionary); 

No article or example mentions having to do this, though. So my impression is that I either am doing something wrong or I am missing some simple step like merging the Brushes.xaml into some ResourceDictionary.

Without that snippet I get a warning that the resource could not be found.

Question

Has anybody an idea where I am going wrong or what I am missing to get this working without that last snippet?

FYI: I am using DevExpress 17.2.3 and the ResourceKey Assembly is targeted to .net Framework 4.0

EDIT

Meanwhile, I tried adding the Brushes.xaml to Themes/Generic.xaml in the theme assembly like this:

<ResourceDictionary.MergedDictionaries>     <dxt:ResourceDictionaryEx Source="/DevExpress.Xpf.Themes.Office2016WhiteSE.v17.2;component/Themes/ControlStyles.xaml" />     <dxt:ResourceDictionaryEx Source="/DevExpress.Xpf.Themes.Office2016WhiteSE.v17.2;component/CustomResources/Brushes.xaml" /> </ResourceDictionary.MergedDictionaries> 

It didn't make any difference. Same behavior as before.

1 Answers

Answers 1

Problem solved!

The problem was in the CustomThemeKeyAssembly

The wrong implementation was

public class CustomThemeResourcesThemeKey : ThemeKeyExtensionBase {     public override Assembly Assembly => TypeInTargetAssembly != null ? TypeInTargetAssembly.Assembly : GetType().Assembly; } 

The working implementation is

public class CustomThemeResourcesThemeKey : ThemeKeyExtensionBase<ThemeResourcesThemeKeys> { } 

The breaking difference is the override of the Assembly property. The default implementation makes it work. I did that because it was done so in an example. Support told me to stick with the default implementation and it worked.

Read More

Sunday, July 23, 2017

Change Color of Xamarin Forms Label in C# only, no XAML

Leave a Comment

I have this XAML code:

<StackLayout Grid.Row="0" Grid.Column="0" Padding="15,10,20,10" HorizontalOptions="StartAndExpand" VerticalOptions="CenterAndExpand">    <StackLayout.GestureRecognizers>       <TapGestureRecognizer Tapped="tapFavorites" NumberOfTapsRequired="1" />    </StackLayout.GestureRecognizers>    <Label x:Name="faveLabel" FontFamily="FontAwesome" XAlign="Center" FontSize="23">       <Label.Triggers>          <DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="true">             <Setter Property="TextColor" Value="Red" />          </DataTrigger>          <DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="false">             <Setter Property="TextColor" Value="Gray" />          </DataTrigger>       </Label.Triggers>    </Label> </StackLayout> 

In my C# code I am familar with setting the Text property of the label by simply specifying like this:

sampleLabel.Text = "ABC" 

But this situation is different. Can someone tell me how I can change the color of a label from C# when the label is clicked on.

3 Answers

Answers 1

What about this:

enter image description here

MainPage:

public partial class MainPage : ContentPage {     MyViewModel vm;      public MainPage()     {         InitializeComponent();          vm = new MyViewModel();         BindingContext = vm;          var faveLabel = new Label { FontSize = 24, FontFamily = "FontAwesome", Text = "Tap Here !" };          var trigger1 = new DataTrigger(typeof(Label));         trigger1.Binding = new Binding("Favorite", BindingMode.TwoWay);         trigger1.Value = true;         trigger1.Setters.Add(new Setter { Property = Label.TextColorProperty, Value = Color.Red });          var trigger2 = new DataTrigger(typeof(Label));         trigger2.Binding = new Binding("Favorite", BindingMode.TwoWay);         trigger2.Value = false;         trigger2.Setters.Add(new Setter { Property = Label.TextColorProperty, Value = Color.Gray });          faveLabel.Triggers.Add(trigger1);         faveLabel.Triggers.Add(trigger2);          var sl = new StackLayout {             HorizontalOptions = LayoutOptions.StartAndExpand,             VerticalOptions = LayoutOptions.CenterAndExpand         };          var tgr = new TapGestureRecognizer();         tgr.NumberOfTapsRequired = 1;         tgr.Tapped += tapFavorites;         sl.GestureRecognizers.Add(tgr);          sl.Children.Add(faveLabel);          Content = sl;     }      public void tapFavorites(object sender, EventArgs e)     {         vm.Favorite = !vm.Favorite;     } } 

ViewModel:

public class MyViewModel : INotifyPropertyChanged {     public event PropertyChangedEventHandler PropertyChanged;      private bool favorite;     public bool Favorite     {         get { return favorite; }         set         {             if (value != favorite)             {                 favorite = value;                 NotifyPropertyChanged();             }         }     }     private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")     {         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));     } } 

Answers 2

You can access your faveLabel trough it's name and a GestureRecognizer to it. There you set the TextColor of your label to a different one. Instead of typing the code out after the arrow function you can also provide a function.

faveLabel.GestureRecognizers.Add( new TapGestureRecognizer { Command = new Command( () => faveLabel.TextColor = Color.Red ) }); 

Instead of typing the full code out after the arrow function you can also provide a function.

... { Command = new Command(() => OnLabelClicked() ) } 

Here is the link to the official Xamarin documentation for the (Tap)GestureRecognizers.

Answers 3

If you do things in xaml then triggers is the way to go but if you do it in code you can do it either way - with or without triggers

You can keep Favorite and/or Label text color in model and do binding or not. If you have model then you can also bind tapFavorites as Marimba showed

public partial class MainPage : ContentPage {     Label faveLabel;     bool favorite = false;      public MainPage()     {         InitializeComponent();          faveLabel = new Label { FontSize = 24, FontFamily = "FontAwesome", Text = "Tap Here !" };          var sl = new StackLayout {             HorizontalOptions = LayoutOptions.StartAndExpand,             VerticalOptions = LayoutOptions.CenterAndExpand         };          var tgr = new TapGestureRecognizer();         tgr.NumberOfTapsRequired = 1;         tgr.Tapped += tapFavorites;         sl.GestureRecognizers.Add(tgr);          sl.Children.Add(faveLabel);          Content = sl;     }      public void tapFavorites(object sender, EventArgs e)     {         favorite = ! favorite;         faveLabel.TextColor = favorite ? Color.Red : Color.Gray;     } } 
Read More

Wednesday, March 1, 2017

Areo Glass Effect and windowStyle set to none causes widow resize to not function properly

Leave a Comment

Areo Glass Effect and windowStyle set to none and AllowTransparency causes widow resize to not function properly

After adding the Areo Glass theme to my window and setting WindowState to None the window does not resize properly. I can go as large as I want but when resizing down smaller the glass effect stays the same width and height.

For example I click Maximize. The window Expands to the full screen size. But when restoring my window restores back down but not the glass effect.

All I really want is the blur effect. I Don't care about the glass, but this seems to be the only way I can get a transparent blur.

How can I fix this? This is driving me nuts! Please Help.

AnyOne???

xaml

    <Window x:Class="WpfApplication2.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         Title="MainWindow" Height="350" Width="525" AllowsTransparency="True" WindowStyle="None" ResizeMode="CanResizeWithGrip" Background="Transparent">     <Border BorderThickness="1" Margin="0,35,0,0" BorderBrush="Orange">     <Grid Background="#0CFFA500">              <DockPanel VerticalAlignment="Top" HorizontalAlignment="Stretch" Height="35" Background="#4effffff">             <DockPanel.Resources>                 <Style x:Key="WindowIconStyle" TargetType="{x:Type Button}">                     <Setter Property="FontSize" Value="16" />                     <Setter Property="Foreground" Value="#444" />                     <Setter Property="Height" Value="30"></Setter>                     <Setter Property="Width" Value="30"></Setter>                     <Setter Property="FontFamily" Value="Webdings"></Setter>                     <Setter Property="Background" Value="#ff0000"></Setter>                     <Setter Property="Template">                         <Setter.Value>                             <ControlTemplate TargetType="{x:Type Button}">                                 <Border BorderBrush="Transparent" BorderThickness="0.5,0,0.5,0">                                     <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>                                 </Border>                             </ControlTemplate>                         </Setter.Value>                     </Setter>                     <Style.Triggers>                         <Trigger Property="IsMouseOver" Value="True">                             <Setter Property="Background" Value="#77abff" />                             <Setter Property="Foreground" Value="#000000" />                             <Setter Property="Template">                                 <Setter.Value>                                     <ControlTemplate TargetType="{x:Type Button}">                                         <Border BorderBrush="Black" BorderThickness="1,0,1,0">                                             <Border.Background>                                                 <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">                                                     <GradientStop Color="Black" Offset="1"/>                                                     <GradientStop Color="White" Offset="0.952"/>                                                     <GradientStop Color="Black" Offset="0"/>                                                     <GradientStop Color="#FFF7F7F7" Offset="0.044"/>                                                 </LinearGradientBrush>                                             </Border.Background>                                             <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>                                         </Border>                                     </ControlTemplate>                                 </Setter.Value>                             </Setter>                         </Trigger>                         <Trigger  Property="IsPressed" Value="True">                             <Setter Property="Template">                                 <Setter.Value>                                     <ControlTemplate TargetType="{x:Type Button}">                                         <Border BorderBrush="#444" BorderThickness="1,0,1,0">                                             <Border.Background>                                                 <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">                                                     <GradientStop Color="#444" Offset="1"/>                                                     <GradientStop Color="#ffececec" Offset="0.952"/>                                                     <GradientStop Color="#444" Offset="0"/>                                                     <GradientStop Color="#ffececec" Offset="0.044"/>                                                 </LinearGradientBrush>                                             </Border.Background>                                             <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>                                         </Border>                                     </ControlTemplate>                                 </Setter.Value>                             </Setter>                         </Trigger>                     </Style.Triggers>                 </Style>             </DockPanel.Resources>             <Button DockPanel.Dock="Right" VerticalAlignment="Center" HorizontalAlignment="Right" Click="TriggerClose" Style="{StaticResource WindowIconStyle}" Content="r" />             <Button x:Name="btnMaximize" DockPanel.Dock="Right" VerticalAlignment="Center" HorizontalAlignment="Right" Click="TriggerMaximize" Style="{StaticResource WindowIconStyle}"  Content="c" />             <Button DockPanel.Dock="Right" VerticalAlignment="Center" HorizontalAlignment="Right" Click="TriggerMinimize" Style="{StaticResource WindowIconStyle}" Content="0" />             <StatusBar Background="Transparent" MouseDoubleClick="TriggerMaximize" MouseMove="TriggerMoveWindow" >                 <TextBlock DockPanel.Dock="Left" x:Name="txtTitle" Text="Title" FontSize="16" Padding="10,0,0,0"/>             </StatusBar>         </DockPanel>             <Border BorderThickness="0,1,0,0" Margin="0,35,0,0" BorderBrush="#f7000000">          </Border>     </Grid>     </Border> </Window> 

C#

using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Input; using System.Windows.Interop;   namespace WpfApplication2 {      public partial class MainWindow : Window {          #region Constants          private System.Windows.Window me { get; set; }         private const int WM_DWMCOMPOSITIONCHANGED = 0x031E;         private const int DWM_BB_ENABLE = 0x1;          #endregion //Constants          #region Structures         [StructLayout(LayoutKind.Sequential)]         private struct DWM_BLURBEHIND {             public int dwFlags;             public bool fEnable;             public IntPtr hRgnBlur;             public bool fTransitionOnMaximized;         }          [StructLayout(LayoutKind.Sequential)]         private struct MARGINS {             public int cxLeftWidth;             public int cxRightWidth;             public int cyTopHeight;             public int cyBottomHeight;         }         #endregion //Structures          #region APIs          [DllImport("dwmapi.dll", PreserveSig = false)]         private static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind);         [DllImport("dwmapi.dll")]         private static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMargins);         [DllImport("dwmapi.dll", PreserveSig = false)]         private static extern bool DwmIsCompositionEnabled();          #endregion //APIs          public MainWindow() {             SourceInitialized += OnSourceInitialized;             InitializeComponent();         }          private void OnSourceInitialized(object sender, EventArgs eventArgs) {             me = (Window)sender;             if (Environment.OSVersion.Version.Major >= 6) {                 var hwnd = new WindowInteropHelper(me).Handle;                 var hs = HwndSource.FromHwnd(hwnd);                 hs.CompositionTarget.BackgroundColor = System.Windows.Media.Colors.Transparent;                  hs.AddHook(new HwndSourceHook(this.WndProc));                 this.InitializeGlass(hwnd);             }          }          public System.Windows.Media.Color GetAreoColor() {             int icolor = (int)Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM", "ColorizationColor", null);             var c = System.Drawing.Color.FromArgb(icolor);             return System.Windows.Media.Color.FromArgb(c.A, c.R, c.G, c.B);         }           private static String ConverterToHex(System.Drawing.Color c) {             return String.Format("#{0}{1}{2}", c.R.ToString("X2"), c.G.ToString("X2"), c.B.ToString("X2"));         }          #region Methods          #region InitializeGlass         public void InitializeGlass(IntPtr hwnd) {             if (!DwmIsCompositionEnabled())                 return;              // fill the background with glass             var margins = new MARGINS();             margins.cxLeftWidth = margins.cxRightWidth = margins.cyBottomHeight = margins.cyTopHeight = -1;             DwmExtendFrameIntoClientArea(hwnd, ref margins);              // initialize blur for the window             DWM_BLURBEHIND bbh = new DWM_BLURBEHIND();             bbh.fEnable = true;             // bbh.fTransitionOnMaximized = true;              bbh.dwFlags = DWM_BB_ENABLE;             DwmEnableBlurBehindWindow(hwnd, ref bbh);         }         #endregion //InitializeGlass          #region WndProc         private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {             if (msg == WM_DWMCOMPOSITIONCHANGED) {                 this.InitializeGlass(hwnd);                 handled = false;             }              return IntPtr.Zero;         }         #endregion //WndProc          #endregion //Methods           private void TriggerMoveWindow(object sender, MouseEventArgs e) {             if (e.LeftButton == MouseButtonState.Pressed) {                 if (WindowState == System.Windows.WindowState.Maximized) {                     WindowState = System.Windows.WindowState.Normal;                      double pct = PointToScreen(e.GetPosition(this)).X / System.Windows.SystemParameters.PrimaryScreenWidth;                     Top = 0;                     Left = e.GetPosition(this).X - (pct * Width);                 }                  Application.Current.MainWindow.DragMove();             }         }          private void TriggerMaximize(object sender, EventArgs e) {             if (WindowState == System.Windows.WindowState.Maximized) {                 WindowState = System.Windows.WindowState.Normal;                 btnMaximize.FontFamily = new System.Windows.Media.FontFamily("Webdings");                 btnMaximize.Content = "c";             } else if (WindowState == System.Windows.WindowState.Normal) {                 WindowState = System.Windows.WindowState.Maximized;                 btnMaximize.FontFamily = new System.Windows.Media.FontFamily("Wingdings");                 btnMaximize.Content = "r";                 InvalidateVisual();             }         }          private void TriggerClose(object sender, RoutedEventArgs e) {                 Close();         }          private void TriggerMinimize(object sender, RoutedEventArgs e) {             WindowState = System.Windows.WindowState.Minimized;         }     } } 

enter image description here

1 Answers

Answers 1

It seems that AllowsTransparency == True is the source of this behavior. Therefore you can remove it. However, you should set the Opacity of Backgroud Brush to be zero:

<Window.Background>     <SolidColorBrush Opacity="0" Color="Transparent"/> </Window.Background> 

This along with setting CompositionTarget.BackgroundColor to be transparent, and also using DwmEnableBlurBehindWindow function will make a similar result to setting AllowsTransparency == True.

However, with these modifications, the look of the window is not very pleasant because of its border. The Border will go away if you set ResizeMode=="NoResize". However, in this case, you should implement resizing yourself. Fortunately, this is easy by adding a Thumb and handling DragDelta event. Here is the full code:

Xaml

 <Window x:Class="Test1.MainWindow"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns:local="clr-namespace:Test1"      mc:Ignorable="d"     xmlns:sys="clr-namespace:System;assembly=mscorlib"     Title="MainWindow" Name="window"      Height="350" Width="525" WindowStyle="None" ResizeMode="NoResize" > <Window.Background>     <SolidColorBrush Opacity="0" Color="Transparent"/> </Window.Background>  <Grid>     <Thumb DockPanel.Dock="Bottom" DragDelta="Thumb_DragDelta" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="8" Height="8" Cursor="SizeNWSE" Background="Red" Panel.ZIndex="4"/>     <Border BorderThickness="1" BorderBrush="Orange" Margin="0,0,0,0">         <Grid Background="#0CFFA500">             <DockPanel VerticalAlignment="Top" HorizontalAlignment="Stretch" Height="35" Background="#4effffff">                 <DockPanel.Resources>                     <Style x:Key="WindowIconStyle" TargetType="{x:Type Button}">                         <Setter Property="FontSize" Value="16" />                         <Setter Property="Foreground" Value="#444" />                         <Setter Property="Height" Value="30"></Setter>                         <Setter Property="Width" Value="30"></Setter>                         <Setter Property="FontFamily" Value="Webdings"></Setter>                         <Setter Property="Background" Value="#ff0000"></Setter>                         <Setter Property="Template">                             <Setter.Value>                                 <ControlTemplate TargetType="{x:Type Button}">                                     <Border BorderBrush="Transparent" BorderThickness="0.5,0,0.5,0">                                         <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>                                     </Border>                                 </ControlTemplate>                             </Setter.Value>                         </Setter>                         <Style.Triggers>                             <Trigger Property="IsMouseOver" Value="True">                                 <Setter Property="Background" Value="#77abff" />                                 <Setter Property="Foreground" Value="#000000" />                                 <Setter Property="Template">                                     <Setter.Value>                                         <ControlTemplate TargetType="{x:Type Button}">                                             <Border BorderBrush="Black" BorderThickness="1,0,1,0">                                                 <Border.Background>                                                     <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">                                                         <GradientStop Color="Black" Offset="1"/>                                                         <GradientStop Color="White" Offset="0.952"/>                                                         <GradientStop Color="Black" Offset="0"/>                                                         <GradientStop Color="#FFF7F7F7" Offset="0.044"/>                                                     </LinearGradientBrush>                                                 </Border.Background>                                                 <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>                                             </Border>                                         </ControlTemplate>                                     </Setter.Value>                                 </Setter>                             </Trigger>                             <Trigger  Property="IsPressed" Value="True">                                 <Setter Property="Template">                                     <Setter.Value>                                         <ControlTemplate TargetType="{x:Type Button}">                                             <Border BorderBrush="#444" BorderThickness="1,0,1,0">                                                 <Border.Background>                                                     <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">                                                         <GradientStop Color="#444" Offset="1"/>                                                         <GradientStop Color="#ffececec" Offset="0.952"/>                                                         <GradientStop Color="#444" Offset="0"/>                                                         <GradientStop Color="#ffececec" Offset="0.044"/>                                                     </LinearGradientBrush>                                                 </Border.Background>                                                 <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>                                             </Border>                                         </ControlTemplate>                                     </Setter.Value>                                 </Setter>                             </Trigger>                         </Style.Triggers>                     </Style>                 </DockPanel.Resources>                 <Button DockPanel.Dock="Right" VerticalAlignment="Center" HorizontalAlignment="Right" Click="TriggerClose" Style="{StaticResource WindowIconStyle}" Content="r" />                 <Button x:Name="btnMaximize" DockPanel.Dock="Right" VerticalAlignment="Center" HorizontalAlignment="Right" Click="TriggerMaximize" Style="{StaticResource WindowIconStyle}"  Content="c" />                 <Button DockPanel.Dock="Right" VerticalAlignment="Center" HorizontalAlignment="Right" Click="TriggerMinimize" Style="{StaticResource WindowIconStyle}" Content="0" />                 <StatusBar Background="Transparent" MouseDoubleClick="TriggerMaximize" MouseMove="TriggerMoveWindow" >                     <TextBlock DockPanel.Dock="Left" x:Name="txtTitle" Text="Title" FontSize="16" Padding="10,0,0,0"/>                 </StatusBar>             </DockPanel>             <Border BorderThickness="0,1,0,0" Margin="0,35,0,0" BorderBrush="#f7000000">              </Border>         </Grid>     </Border> </Grid> </Window> 

CS Code

public partial class MainWindow : Window {      private const int WM_DWMCOMPOSITIONCHANGED = 0x031E;     private const int DWM_BB_ENABLE = 0x1;       [StructLayout(LayoutKind.Sequential)]     private struct DWM_BLURBEHIND     {         public int dwFlags;         public bool fEnable;         public IntPtr hRgnBlur;         public bool fTransitionOnMaximized;     }      [StructLayout(LayoutKind.Sequential)]     private struct MARGINS     {         public int cxLeftWidth;         public int cxRightWidth;         public int cyTopHeight;         public int cyBottomHeight;     }       [DllImport("dwmapi.dll", PreserveSig = false)]     private static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind);     [DllImport("dwmapi.dll")]     private static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMargins);     [DllImport("dwmapi.dll", PreserveSig = false)]     private static extern bool DwmIsCompositionEnabled();      public MainWindow()     {          InitializeComponent();         SourceInitialized += OnSourceInitialized;      }       private void OnSourceInitialized(object sender, EventArgs eventArgs)     {         var hwnd = new WindowInteropHelper(this).Handle;         var hs = HwndSource.FromHwnd(hwnd);         hs.CompositionTarget.BackgroundColor = System.Windows.Media.Colors.Transparent;          var margins = new MARGINS();         margins.cxLeftWidth = margins.cxRightWidth = margins.cyTopHeight = margins.cyBottomHeight = -1;          DwmExtendFrameIntoClientArea(hwnd, ref margins);          DWM_BLURBEHIND bbh = new DWM_BLURBEHIND();         bbh.fEnable = true;         bbh.dwFlags = DWM_BB_ENABLE;         DwmEnableBlurBehindWindow(hwnd, ref bbh);     }      private void TriggerMinimize(object sender, RoutedEventArgs e)     {         WindowState = System.Windows.WindowState.Minimized;     }      private void TriggerMoveWindow(object sender, MouseEventArgs e)     {         if (e.LeftButton == MouseButtonState.Pressed)         {             if (WindowState == System.Windows.WindowState.Maximized)             {                 WindowState = System.Windows.WindowState.Normal;                  double pct = PointToScreen(e.GetPosition(this)).X / System.Windows.SystemParameters.PrimaryScreenWidth;                 Top = 0;                 Left = e.GetPosition(this).X - (pct * Width);             }              Application.Current.MainWindow.DragMove();         }     }      private void TriggerMaximize(object sender, EventArgs e)     {         if (WindowState == System.Windows.WindowState.Maximized)         {             WindowState = System.Windows.WindowState.Normal;             btnMaximize.FontFamily = new System.Windows.Media.FontFamily("Webdings");             btnMaximize.Content = "c";         }         else if (WindowState == System.Windows.WindowState.Normal)         {             WindowState = System.Windows.WindowState.Maximized;             btnMaximize.FontFamily = new System.Windows.Media.FontFamily("Wingdings");             btnMaximize.Content = "r";             InvalidateVisual();         }     }      private void TriggerClose(object sender, RoutedEventArgs e)     {         Close();     }      private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)     {         this.Height += e.VerticalChange;         this.Width += e.HorizontalChange;     } } 

You can see the result:

https://i.stack.imgur.com/Rvtp3.gif

Read More

Wednesday, February 22, 2017

XAML Designer displays property name instead of Designer Data (d:DataContext) when Binding

Leave a Comment

Context

I want my UserControl (RepositoryContainer) to be filled up with data when on XAML Designer.

I created a file named RepositoryContainerDesignData.xaml (it is in the same folder as the RepositoryContainer.xaml) and set it as d:DataContext to the UserControl.

But instead of displaying the data, XAML Designer displays the property name.

Here's a minimal example:

Design Data (RepositoryContainerDesignData.xaml)

<local:RepositoryContainer xmlns:local="clr-namespace:SystemSpecs.View.UserControls"                            Title="My Repository Title" /> 

User Control (RepositoryContainer.xaml)

<UserControl x:Class="SystemSpecs.View.UserControls.RepositoryContainer"                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"                  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"                  xmlns:local="clr-namespace:SystemSpecs.View.UserControls"                 mc:Ignorable="d"                  d:DesignHeight="100" d:DesignWidth="500"                 d:DataContext="{d:DesignData Source=RepositoryContainerDesignData.xaml}"                 DataContext="{Binding RelativeSource={RelativeSource Self}}">      <Grid>         <TextBlock Text="{Binding Path=Title}" FontSize="24" Foreground="White" HorizontalAlignment="Center" />     </Grid> </UserControl> 

Code-behind

using System.Windows.Controls;  namespace SystemSpecs.View.UserControls {     public partial class RepositoryContainer : UserControl     {         public string Title { get; set; }          public RepositoryContainer()         {             InitializeComponent();         }     } } 

Expected output:

Expected output

Output:

Output

Already tried:

Environment info:

  • Windows 10 Pro x64
  • Visual Studio Community 2015 (Version 14.9.25431.01 Update 3)
  • Microsoft .NET Framework 4.6.01586
  • More info at a Pastebin RAW to keep post clean

Am I missing something?

PS

If I create a class (e.g. public class RepositoryContainerData), create a property called Title and set an instance of this class as d:DataContext (d:DataContext="{d:DesignInstance local:RepositoryContainerData, IsDesignTimeCreatable=True}") it works as expected.

2 Answers

Answers 1

What you're trying to do works for me with possibly some minor changes. I created a new app called WpfApplication2.

RepositoryContainerDesignData.xaml contains:

<wpfApplication2:RepositoryContainer      xmlns:wpfApplication2="clr-namespace:WpfApplication2"     Title="My repository title"> </wpfApplication2:RepositoryContainer> 

The file properties are set to:

enter image description here

The control definition is

<UserControl x:Class="WpfApplication2.RepositoryContainer"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"               xmlns:d="http://schemas.microsoft.com/expression/blend/2008"              d:DataContext="{d:DesignData Source=RepositoryContainerDesignData.xaml}"              mc:Ignorable="d"               d:DesignHeight="300" d:DesignWidth="300">     <Grid Background="Bisque">         <TextBlock Text="{Binding Path=Title}" FontSize="24"                     HorizontalAlignment="Center" VerticalAlignment="Center" />     </Grid> </UserControl> 

The result in the designer is

enter image description here

Not something I would usually do but I've learned something :)

Answers 2

You should use dependency properties in WPF usercontrols as they have change notification.

    public static DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(RepositoryContainer), new FrameworkPropertyMetadata(new PropertyChangedCallback(Title_Changed)));      public string Title     {         get { return (string)GetValue(TitleProperty); }         set { SetValue(TitleProperty, value); }     }       private static void Title_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)     {         RepositoryContainer thisClass = (RepositoryContainer)o;         thisClass.SetTitle();     }      private void SetTitle()     {         //Put Instance Title Property Changed code here     } 

Just replace your Title property with the code above, nothing should have to be added to make it work. SetTitle() only needs code if you need to react to the Title changed in code.

I have a c# code snippet that I created a long time ago that can make dependency properties easily, just let me know if you want it.

Read More

Friday, February 10, 2017

Why in my WPF view is the Content text of my Label control not visible?

Leave a Comment

I have the following markup:

<StackPanel Grid.Row="0" Orientation="Horizontal">     <StackPanel Orientation="Horizontal" Visibility="{Binding OrgListVisibility}">         <Label Content="Org:" />         <ComboBox ItemsSource="{Binding OrgSelectList, NotifyOnSourceUpdated=True}" SelectedValuePath="Key" DisplayMemberPath="Value" SelectedItem="{Binding OrgId}" />     </StackPanel>     <StackPanel Orientation="Horizontal" Visibility="{Binding BranchListVisibility}">         <TextBlock Text="Branch:" Style="{StaticResource FormLabel}" />         <ComboBox x:Name="BranchList" ItemsSource="{Binding BranchSelectList}" SelectedValuePath="Key" DisplayMemberPath="Value" SelectedItem="{Binding BranchId}" />     </StackPanel> </StackPanel> 

Yet when I run the app, only the text from the TextBlock is visible, and not that of the Label. The latter is in the Visual Tree, with a TextBlock deep down, but that is as far as I can see.

AS REQUESTED: Here is the style for FormLabel:

<Style TargetType="TextBlock" x:Key="FormLabel">     <Setter Property="Height" Value="20" />     <Setter Property="Margin" Value="10" />     <Setter Property="TextAlignment" Value="Right" />     <Setter Property="VerticalAlignment" Value="Center" /> </Style> 

A SIMILAR PROBLEM: I found an almost similar problem with a combobox when I bound it to a collection of instances of a generic class. The items' text simply did not show, but they were present in the comboboxes. Selecting on the one by knowing the position of my sought item correctly cascaded to the 2nd combobox, which had visible items, and I could see the correct but invisible item had been selected.

As soon as I change the item source to a list of non-generic objects, the items in the dropdown were visible again.

4 Answers

Answers 1

The code looks fine and as you have mentioned in the comments section that it takes layout space then it may very well happen that the color of your label and the background color of the containing layout be same.

To troubleshoot this, try giving some different background and foreground colors e.g. red or blue to the Label. Hope this helps

Answers 2

The Label would take up layout space while not being visible when its Visibility == Hidden. You should check and make sure that your application does not define a global style (one with no Key) for TargetType="Label" where this value could be set:

<Style TargetType="Label"> !!!note that this has no 'Key' associated       [...]     <Setter Property="Visibility" Value="Hidden" />       [...] </Style> 

This would not need to be in the same xaml file in order to be automatically applied, you should check the global dictionary or any other ResourceDictionary linked in the file.

Answers 3

Ctrl+Q -> Live Visual Tree

Then hit the "pick element" button and select your label. Check the following properties:

Visibility
Opacity
Content

Also check the child elements of the Label. Setting the Content should result in a tree like this:

Label visual tree

If a default style has changed the control template, you might not see the TextBlock as a child here. Also drill into the TextBlock and make sure it has the right Text property, then make sure it and all its parents have the right Opacity and Visibility . Also make sure that the inner TextBlock has space allocated to it by selecting it and turning on the highlighting feature in the live visual tree window.

Answers 4

Can you try this code to see if it works?

 <Grid Grid.Row="0">     <Grid.ColumnDefinitions>         <ColumnDefinition Width="Auto"/>         <ColumnDefinition Width="Auto"/>     </Grid.ColumnDefinitions>      <StackPanel Grid.Column="0"                 Orientation="Horizontal" Visibility="{Binding OrgListVisibility}">         <Label Content="Org:" />         <ComboBox ItemsSource="{Binding OrgSelectList, NotifyOnSourceUpdated=True}"                        SelectedValuePath="Key"                        DisplayMemberPath="Value"                        SelectedItem="{Binding OrgId}" />     </StackPanel>     <StackPanel Grid.Column="1"                 Orientation="Horizontal" Visibility="{Binding BranchListVisibility}">         <TextBlock Text="Branch:" Style="{StaticResource FormLabel}" />         <ComboBox x:Name="BranchList"                        ItemsSource="{Binding BranchSelectList}"                        SelectedValuePath="Key"                        DisplayMemberPath="Value"                        SelectedItem="{Binding BranchId}" />     </StackPanel> </Grid> 
Read More

Tuesday, January 10, 2017

How does the W10 News app stretch the items in the gridview?

Leave a Comment

I'm trying to create a gridview like in the default News app in Windows 10. As far as I know I have to set the ItemHeight an ItemWidth for the VariableSizedWrapGrid. But then it does not stretch the items to fit the full grid width, while the News app does do that as you can see in the pictures below. How do they do that? Is it a special custom control? Widescreen, 4 columns and items are quite wide

Narrowscreen, 3 small columns

4 Answers

Answers 1

I will just give you the concept:

 +---------+ +---------+ +---------+  |  small  | |         | |         | +---------+ |         | |         | --- gap --- | medium  | |         | +---------+ |         | |         | |  small  | |         | |   big   | +---------+ +---------+ |         | --- gap --- --- gap --- |         | +---------+ +---------+ |         | |  small  | |  small  | |         | +---------+ +---------+ +---------+ --- gap --- --- gap --- --- gap --- 

So we only have 3 different boxes for presentation with a known height. The view itself can decide (codebehind) which template is used to present the content.

  • small: headline with a small thumbnail
  • medium: small image with headline
  • large: image with headline and some text from article

Alle items are arranged in groups by 5 to 9 items for each group. The groups are presented inside an ItemsControl and each group is presented by a WrapPanel (vertical oriantation).

Lets see that for some rows:

  • 2 columns, 6 items
 lllll  mmmmm lllll  mmmmm lllll  mmmmm lllll lllll  sssss  lllll  mmmmm lllll  mmmmm lllll  mmmmm lllll lllll  sssss 
  • 3 columns, 6 items
 lllll  lllll  mmmmm lllll  lllll  mmmmm lllll  lllll  mmmmm lllll  lllll   lllll  lllll  lllll               lllll mmmmm  mmmmm  lllll mmmmm  mmmmm  lllll mmmmm  mmmmm  lllll 
  • 4 columns, 6 items
 lllll  lllll  lllll  sssss lllll  lllll  lllll lllll  lllll  lllll  sssss lllll  lllll  lllll lllll  lllll  lllll  sssss 
  • 5 columns, 6 items
 mmmmm  mmmmm  mmmmm  mmmmm  sssss mmmmm  mmmmm  mmmmm  mmmmm mmmmm  mmmmm  mmmmm  mmmmm  sssss 

So we need three DataTemplates for the content items, some templates for the WrapPanel and some logic inside the view to group the items into rows and the template mangement for the WrapPanel and the items inside.

Here a simple XAML PoC just to test the concept:

<Grid>     <ScrollViewer>         <ItemsControl>             <ItemsControl.Resources>                 <Style x:Key="col" TargetType="WrapPanel">                     <Setter Property="Orientation" Value="Vertical"/>                     <Setter Property="ItemWidth" Value="80"/>                 </Style>                  <Style x:Key="content" TargetType="Border">                     <Setter Property="Margin" Value="5,5"/>                 </Style>                 <Style x:Key="small" TargetType="Border" BasedOn="{StaticResource content}">                     <Setter Property="Background" Value="Orange"/>                     <Setter Property="Height" Value="30"/>                 </Style>                 <Style x:Key="medium" TargetType="Border" BasedOn="{StaticResource content}">                     <Setter Property="Background" Value="Green"/>                     <Setter Property="Height" Value="70"/>                 </Style>                 <Style x:Key="large" TargetType="Border" BasedOn="{StaticResource content}">                     <Setter Property="Background" Value="Red"/>                     <Setter Property="Height" Value="110"/>                 </Style>                  <Style x:Key="2col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                     <Setter Property="Height" Value="240"/>                 </Style>                  <Style x:Key="3col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                     <Setter Property="Height" Value="200"/>                 </Style>                  <Style x:Key="4col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                     <Setter Property="Height" Value="120"/>                 </Style>                  <Style x:Key="5col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                     <Setter Property="Height" Value="80"/>                 </Style>               </ItemsControl.Resources>             <!-- first row -->             <WrapPanel Style="{StaticResource 5col6items}">                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource small}"/>                 <Border Style="{StaticResource small}"/>             </WrapPanel>             <!-- second row -->             <WrapPanel Style="{StaticResource 4col6items}">                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource small}"/>                 <Border Style="{StaticResource small}"/>                 <Border Style="{StaticResource small}"/>             </WrapPanel>             <!-- third row -->             <WrapPanel Style="{StaticResource 3col6items}">                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource large}"/>             </WrapPanel>             <!-- fourth row -->             <WrapPanel Style="{StaticResource 2col6items}">                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource large}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource small}"/>                 <Border Style="{StaticResource medium}"/>                 <Border Style="{StaticResource small}"/>             </WrapPanel>         </ItemsControl>     </ScrollViewer> </Grid> 

and the lookalike

enter image description here

Update

A very simple ProofOfConcept with stretching and templating on resize

<Window x:Class="WpfApp1.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"         xmlns:local="clr-namespace:WpfApp1"         mc:Ignorable="d"         Title="MainWindow" Height="350" Width="525">     <Grid>         <ScrollViewer>             <ItemsControl x:Name="ItemsPresenter" SizeChanged="ItemsPresenter_SizeChanged">                 <ItemsControl.Resources>                     <Style x:Key="col" TargetType="WrapPanel">                         <Setter Property="Orientation" Value="Vertical"/>                         <Setter Property="ItemWidth" Value="{Binding ColumnWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}"/>                     </Style>                      <Style x:Key="content" TargetType="TextBlock">                         <Setter Property="Margin" Value="5"/>                         <Setter Property="HorizontalAlignment" Value="Stretch"/>                         <Setter Property="TextAlignment" Value="Center"/>                         <Setter Property="VerticalAlignment" Value="Stretch"/>                     </Style>                     <Style x:Key="small" TargetType="TextBlock" BasedOn="{StaticResource content}">                         <Setter Property="Background" Value="LightBlue"/>                         <Setter Property="Height" Value="30"/>                     </Style>                     <Style x:Key="medium" TargetType="TextBlock" BasedOn="{StaticResource content}">                         <Setter Property="Background" Value="LightGreen"/>                         <Setter Property="Height" Value="70"/>                     </Style>                     <Style x:Key="large" TargetType="TextBlock" BasedOn="{StaticResource content}">                         <Setter Property="Background" Value="LightSalmon"/>                         <Setter Property="Height" Value="110"/>                     </Style>                      <Style x:Key="1col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                         <Setter Property="Height" Value="480"/>                     </Style>                      <Style x:Key="2col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                         <Setter Property="Height" Value="240"/>                     </Style>                      <Style x:Key="3col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                         <Setter Property="Height" Value="200"/>                     </Style>                      <Style x:Key="4col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                         <Setter Property="Height" Value="120"/>                     </Style>                      <Style x:Key="5col6items" TargetType="WrapPanel" BasedOn="{StaticResource col}">                         <Setter Property="Height" Value="80"/>                     </Style>                   </ItemsControl.Resources>                 <!-- first row -->                 <WrapPanel >                     <TextBlock>1</TextBlock>                     <TextBlock>2</TextBlock>                     <TextBlock>3</TextBlock>                     <TextBlock>4</TextBlock>                     <TextBlock>5</TextBlock>                     <TextBlock>6</TextBlock>                 </WrapPanel>                 <!-- second row -->                 <WrapPanel >                     <TextBlock>7</TextBlock>                     <TextBlock>8</TextBlock>                     <TextBlock>9</TextBlock>                     <TextBlock>10</TextBlock>                     <TextBlock>11</TextBlock>                     <TextBlock>12</TextBlock>                 </WrapPanel>                 <!-- third row -->                 <WrapPanel >                     <TextBlock>13</TextBlock>                     <TextBlock>14</TextBlock>                     <TextBlock>15</TextBlock>                     <TextBlock>16</TextBlock>                     <TextBlock>17</TextBlock>                     <TextBlock>18</TextBlock>                 </WrapPanel>             </ItemsControl>         </ScrollViewer>     </Grid> </Window> 

and the codebehind

public partial class MainWindow : Window {     public MainWindow()     {         InitializeComponent( );     }      public int ColumnCount     {         get { return (int) GetValue( ColumnCountProperty ); }         private set { SetValue( ColumnCountProperty, value ); }     }      // Using a DependencyProperty as the backing store for ColumnCount.  This enables animation, styling, binding, etc...     public static readonly DependencyProperty ColumnCountProperty =         DependencyProperty.Register( "ColumnCount", typeof( int ), typeof( MainWindow ), new PropertyMetadata( 1 ) );      public double ColumnWidth     {         get { return (double) GetValue( ColumnWidthProperty ); }         private set { SetValue( ColumnWidthProperty, value ); }     }      // Using a DependencyProperty as the backing store for ColumnWidth.  This enables animation, styling, binding, etc...     public static readonly DependencyProperty ColumnWidthProperty =         DependencyProperty.Register( "ColumnWidth", typeof( double ), typeof( MainWindow ), new PropertyMetadata( (double) 100 ) );      public double ColumnMinWidth     {         get { return (double) GetValue( ColumnMinWidthProperty ); }         set         {             SetValue( ColumnMinWidthProperty, value );             CalculateColumnLayout( );         }     }      // Using a DependencyProperty as the backing store for ColumnMinWidth.  This enables animation, styling, binding, etc...     public static readonly DependencyProperty ColumnMinWidthProperty =         DependencyProperty.Register( "ColumnMinWidth", typeof( double ), typeof( MainWindow ), new PropertyMetadata( (double) 200 ) );      public double ColumnMaxWidth     {         get { return (double) GetValue( ColumnMaxWidthProperty ); }         set         {             SetValue( ColumnMaxWidthProperty, value );             CalculateColumnLayout( );         }     }      // Using a DependencyProperty as the backing store for ColumnMaxWidth.  This enables animation, styling, binding, etc...     public static readonly DependencyProperty ColumnMaxWidthProperty =         DependencyProperty.Register( "ColumnMaxWidth", typeof( double ), typeof( MainWindow ), new PropertyMetadata( (double) 250 ) );      private void CalculateColumnLayout()     {         int colCount = ColumnCount;         double totalWidth = ItemsPresenter.ActualWidth;         double colWidth = totalWidth / colCount;          while ( colCount > 1 && colWidth < Math.Min( ColumnMinWidth, ColumnMaxWidth ) )         {             colCount--;             colWidth = totalWidth / colCount;         }          while ( colCount < 5 && colWidth > Math.Max( ColumnMinWidth, ColumnMaxWidth ) )         {             colCount++;             colWidth = totalWidth / colCount;         }          if ( ColumnCount != colCount )         {             ColumnCount = colCount;             StyleItemsPresenterItems( );         }         ColumnWidth = colWidth;     }      private Dictionary<int, string[]> _styles = new Dictionary<int, string[]>     {         [ 1 ] = new string[] { "medium", "medium", "medium", "medium", "medium", "medium" },         [ 2 ] = new string[] { "large", "medium", "small", "small", "medium", "large" },         [ 3 ] = new string[] { "large", "medium", "medium", "large", "large", "medium" },         [ 4 ] = new string[] { "large", "large", "large", "small", "small", "small" },         [ 5 ] = new string[] { "medium", "medium", "medium", "medium", "small", "small" },     };       private void StyleItemsPresenterItems()     {         foreach ( var pnl in ItemsPresenter.Items.OfType<WrapPanel>( ) )         {             if ( pnl != null )             {                 pnl.Style = ItemsPresenter.Resources[ $"{ColumnCount}col6items" ] as Style;                  foreach ( var item in pnl.Children.OfType<TextBlock>( ).Zip( _styles[ ColumnCount ], ( border, stylename ) => new { border, stylename } ) )                 {                     item.border.Style = ItemsPresenter.Resources[ item.stylename ] as Style;                 }              }         }     }      private void ItemsPresenter_SizeChanged( object sender, SizeChangedEventArgs e )     {         CalculateColumnLayout( );     } } 

and finally the result

enter image description here

Answers 2

According to MSDN the ItemWidth can be set to Auto.

The default value of ItemHeight and ItemWidth is not 0, it is Double.NaN. ItemHeight and ItemWidth support the ability to be an unset "Auto" value. Because ItemHeight and ItemWidth are Double values, Double.NaN is used as a special value to represent this "Auto" behavior. The layout system interprets the "Auto" value to generally mean that the object should be sized to the available size in layout, instead of to a specific pixel value.

I don't know if this will result in the behavior you want though. If it doesn't then you might be able to get it by binding the ItemWidth to a property where you calculate the item width based on the width of the grid. It would look something like this:

float DynamicItemWidth {   get {     int ItemMinimumWidth = 300, margin = 16; //just some guesses     var gridWidth = ...;      var numberOfColumns = gridWidth % ItemMinimumWidth;     var itemWidth = (gridWidth - margin * (numberOfColumns - 1)) / numberOfColumns;      return itemWidth;   } } 

Answers 3

UWP

As an addition to my previous answer where I show the basic concept here a solution for UWP platform using the VariableSizedWrapPanel as mentioned in the question:

The main job is done by

<local:MyGridView      ItemsSource="{Binding}"      ItemTemplateSelector="{StaticResource MyGridTemplateSelector}"      MinItemWidth="300" MaxItemWidth="600"      ScrollViewer.VerticalScrollBarVisibility="Hidden">     <GridView.ItemsPanel>         <ItemsPanelTemplate>             <VariableSizedWrapGrid ItemHeight="180" Orientation="Horizontal"/>         </ItemsPanelTemplate>     </GridView.ItemsPanel> </local:MyGridView> 

along with

MyGridView.cs

using System; using System.Collections.Generic; using System.Linq; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls;  namespace App1 {     public class MyGridView : GridView     {         private int _columnCount = 1;         private double _itemWidth = 100;          public double MinItemWidth         {             get { return (double) GetValue( MinItemWidthProperty ); }             set { SetValue( MinItemWidthProperty, value ); }         }          // Using a DependencyProperty as the backing store for MinItemWidth.  This enables animation, styling, binding, etc...         public static readonly DependencyProperty MinItemWidthProperty =             DependencyProperty.Register( "MinItemWidth", typeof( double ), typeof( MyGridView ), new PropertyMetadata( 100.0 ) );           public double MaxItemWidth         {             get { return (double) GetValue( MaxItemWidthProperty ); }             set { SetValue( MaxItemWidthProperty, value ); }         }          // Using a DependencyProperty as the backing store for MaxItemWidth.  This enables animation, styling, binding, etc...         public static readonly DependencyProperty MaxItemWidthProperty =             DependencyProperty.Register( "MaxItemWidth", typeof( double ), typeof( MyGridView ), new PropertyMetadata( 200.0 ) );           private long _itemsPanelPropertyChangedToken;          public MyGridView()         {             _itemsPanelPropertyChangedToken = RegisterPropertyChangedCallback( ItemsPanelProperty, ItemsPanelChangedAsync );         }          private async void ItemsPanelChangedAsync( DependencyObject sender, DependencyProperty dp )         {             UnregisterPropertyChangedCallback( ItemsPanelProperty, _itemsPanelPropertyChangedToken );             await this.Dispatcher.RunIdleAsync( ItemsPanelChangedCallback );         }          private void ItemsPanelChangedCallback( IdleDispatchedHandlerArgs e )         {             var wg = ItemsPanelRoot as VariableSizedWrapGrid;             if (wg != null)             {                 wg.ItemWidth = _itemWidth;             }         }          protected override void PrepareContainerForItemOverride( DependencyObject element, object item )         {             var itemIndex = this.Items.IndexOf( item );              element.SetValue( VariableSizedWrapGrid.RowSpanProperty, GetRowSpanByColumnCountAndIndex( _columnCount, itemIndex ) );             element.SetValue( VerticalContentAlignmentProperty, VerticalAlignment.Stretch );             element.SetValue( HorizontalContentAlignmentProperty, HorizontalAlignment.Stretch );             base.PrepareContainerForItemOverride( element, item );         }          private static readonly Dictionary<int, int[]> _rowSpanLayout = new Dictionary<int, int[]>         {             [ 1 ] = new int[] { /* 5 */ 2, 2, 2, 2, 2, /* 6 */ 2, 2, 2, 2, 2, 2, /* 7 */ 2, 2, 2, 2, 2, 2, 2, /* 8 */ 2, 2, 2, 2, 2, 2, 2, 2, /* 9 */ 2, 2, 2, 2, 2, 2, 2, 2, 2 },             [ 2 ] = new int[] { /* 5 */ 2, 1, 2, 2, 1, /* 6 */ 3, 3, 3, 2, 2, 2, /* 7 */ 3, 3, 1, 2, 3, 1, 1, /* 8 */ 2, 3, 2, 3, 3, 3, 3, 1, /* 9 */ 3, 2, 1, 3, 2, 2, 3, 1, 1 },             [ 3 ] = new int[] { /* 5 */ 3, 2, 2, 1, 1, /* 6 */ 2, 3, 2, 3, 3, 2, /* 7 */ 3, 3, 3, 2, 1, 2, 1, /* 8 */ 2, 3, 3, 1, 2, 1, 2, 1, /* 9 */ 3, 3, 3, 1, 2, 1, 3, 3, 2 },             [ 4 ] = new int[] { /* 5 */ 2, 2, 1, 2, 1, /* 6 */ 3, 3, 2, 2, 1, 1, /* 7 */ 3, 2, 2, 2, 1, 1, 1, /* 8 */ 3, 3, 3, 3, 2, 2, 2, 2, /* 9 */ 3, 3, 3, 2, 2, 2, 2, 2, 1 },             [ 5 ] = new int[] { /* 5 */ 2, 2, 2, 2, 2, /* 6 */ 2, 2, 2, 1, 2, 1, /* 7 */ 3, 3, 3, 2, 2, 1, 1, /* 8 */ 3, 3, 2, 2, 2, 1, 1, 1, /* 9 */ 3, 2, 2, 2, 2, 1, 1, 1, 1 },         };          private int GetRowSpanByColumnCountAndIndex( int columnCount, int itemIndex )         {             return _rowSpanLayout[ columnCount ][ itemIndex % 35 ];         }          protected override Size MeasureOverride( Size availableSize )         {             System.Diagnostics.Debug.WriteLine( availableSize );              int columnCount = _columnCount;             double availableWidth = availableSize.Width;              double itemWidth = availableWidth / columnCount;              while ( columnCount > 1 && itemWidth < Math.Min( MinItemWidth, MaxItemWidth ) )             {                 columnCount--;                 itemWidth = availableWidth / columnCount;             }              while ( columnCount < 5 && itemWidth > Math.Max( MinItemWidth, MaxItemWidth ) )             {                 columnCount++;                 itemWidth = availableWidth / columnCount;             }              var wg = this.ItemsPanelRoot as VariableSizedWrapGrid;              _itemWidth = itemWidth;             if ( _columnCount != columnCount )             {                 _columnCount = columnCount;                 if ( wg != null )                 {                     Update( );                 }             }              if ( wg != null )             {                 wg.ItemWidth = itemWidth;             }              return base.MeasureOverride( availableSize );         }          // refresh the variablesizedwrapgrid layout         private void Update()         {             if ( !( this.ItemsPanelRoot is VariableSizedWrapGrid ) )                 throw new ArgumentException( "ItemsPanel is not VariableSizedWrapGrid" );              int itemIndex = 0;             foreach ( var container in this.ItemsPanelRoot.Children.Cast<GridViewItem>( ) )             {                 int rowSpan = GetRowSpanByColumnCountAndIndex( _columnCount, itemIndex );                 VariableSizedWrapGrid.SetRowSpan( container, rowSpan );                 itemIndex++;             }              this.ItemsPanelRoot.InvalidateMeasure( );         }     } } 

and

MyGridViewTemplateSelector.cs

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls;  namespace App1 {     public class MyGridViewTemplateSelector : DataTemplateSelector     {         public DataTemplate Small { get; set; }         public DataTemplate Medium { get; set; }         public DataTemplate Large { get; set; }          protected override DataTemplate SelectTemplateCore( object item, DependencyObject container )         {             var rowSpan = container.GetValue( VariableSizedWrapGrid.RowSpanProperty );              int index;             try             {                 dynamic model = item;                 index = model.Index;             }             catch ( Exception )             {                 index = -1;             }             long token = 0;              DependencyPropertyChangedCallback lambda = ( sender, dp ) =>             {                 container.UnregisterPropertyChangedCallback( VariableSizedWrapGrid.RowSpanProperty, token );                  var cp = (ContentControl) container;                 cp.ContentTemplateSelector = null;                 cp.ContentTemplateSelector = this;             };              token = container.RegisterPropertyChangedCallback( VariableSizedWrapGrid.RowSpanProperty, lambda );              switch ( rowSpan )             {                 case 1:                     return Small;                 case 2:                     return Medium;                 case 3:                     return Large;                 default:                     throw new InvalidOperationException( );             }         }          private void Foo( DependencyObject sender, DependencyProperty dp )         {             throw new NotImplementedException( );         }     } } 

To complete here the other files

MainPage.xaml

<Page     x:Class="App1.MainPage"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:local="using:App1"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d">     <Page.Resources>          <DataTemplate x:Key="Small">             <Grid Margin="5">                 <Grid.Background>                     <SolidColorBrush Color="{Binding Path=Color}"/>                 </Grid.Background>                 <StackPanel VerticalAlignment="Top">                     <StackPanel.Background>                         <SolidColorBrush Color="White" Opacity="0.75"/>                     </StackPanel.Background>                      <TextBlock FontSize="15" Margin="10">                         <Run Text="{Binding Path=Index}"/>. <Run Text="{Binding Path=Name}"/>                     </TextBlock>                     <TextBlock Text="Small" TextAlignment="Center"/>                 </StackPanel>             </Grid>         </DataTemplate>          <DataTemplate x:Key="Medium">             <Grid Margin="5">                 <Grid.Background>                     <SolidColorBrush Color="{Binding Path=Color}"/>                 </Grid.Background>                 <StackPanel VerticalAlignment="Top">                     <StackPanel.Background>                         <SolidColorBrush Color="White" Opacity="0.75"/>                     </StackPanel.Background>                      <TextBlock FontSize="15" Margin="10">                         <Run Text="{Binding Path=Index}"/>. <Run Text="{Binding Path=Name}"/>                     </TextBlock>                     <TextBlock Text="Medium" TextAlignment="Center"/>                 </StackPanel>             </Grid>         </DataTemplate>          <DataTemplate x:Key="Large">             <Grid Margin="5">                 <Grid.Background>                     <SolidColorBrush Color="{Binding Path=Color}"/>                 </Grid.Background>                 <StackPanel VerticalAlignment="Top">                     <StackPanel.Background>                         <SolidColorBrush Color="White" Opacity="0.75"/>                     </StackPanel.Background>                      <TextBlock FontSize="15" Margin="10">                         <Run Text="{Binding Path=Index}"/>. <Run Text="{Binding Path=Name}"/>                     </TextBlock>                     <TextBlock Text="Large" TextAlignment="Center"/>                 </StackPanel>             </Grid>          </DataTemplate>         <local:MyGridViewTemplateSelector x:Key="MyGridTemplateSelector"                                           Small="{StaticResource Small}"                                           Medium="{StaticResource Medium}"                                           Large="{StaticResource Large}"/>     </Page.Resources>      <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">         <Grid.RowDefinitions>             <RowDefinition Height="48"/>             <RowDefinition Height="*"/>         </Grid.RowDefinitions>         <Grid.ColumnDefinitions>             <ColumnDefinition Width="48"/>             <ColumnDefinition Width="*"/>         </Grid.ColumnDefinitions>          <!-- top left section -->          <Border Background="#D13438">          </Border>          <!-- top bar -->          <Border Grid.Column="1" Grid.Row="0" Padding="5" Background="#F2F2F2">             <TextBlock Text="MenuBar" VerticalAlignment="Center"/>         </Border>          <!-- left bar -->          <Border Grid.Column="0" Grid.Row="1" Width="48" Background="#2B2B2B">          </Border>          <!-- content -->          <Border Grid.Column="1" Grid.Row="1" Background="#E6E6E6">             <Grid>                 <Grid.RowDefinitions>                     <RowDefinition Height="48"/>                     <RowDefinition Height="*"/>                 </Grid.RowDefinitions>                 <Border Grid.Row="0" Padding="5" Background="#F2F2F2">                     <TextBlock Text="SectionBar" VerticalAlignment="Center"/>                 </Border>                 <ScrollViewer Grid.Row="1">                     <Border Margin="7,7,10,7">                          <!-- the wrapped news items -->                          <local:MyGridView ItemsSource="{Binding}" ItemTemplateSelector="{StaticResource MyGridTemplateSelector}" MinItemWidth="300" MaxItemWidth="600" ScrollViewer.VerticalScrollBarVisibility="Hidden">                             <GridView.ItemsPanel>                                 <ItemsPanelTemplate>                                     <VariableSizedWrapGrid ItemHeight="180" Orientation="Horizontal"/>                                 </ItemsPanelTemplate>                             </GridView.ItemsPanel>                         </local:MyGridView>                      </Border>                 </ScrollViewer>             </Grid>         </Border>     </Grid> </Page> 

MainPage.xaml.cs

using System.Linq; using Windows.UI; using Windows.UI.Xaml.Controls; using System.Reflection;  namespace App1 {     public sealed partial class MainPage : Page     {         public MainPage()         {             this.InitializeComponent( );              // just some sample data              var colors = typeof( Colors )                 .GetRuntimeProperties( )                 .Take( 140 )                 .Select( ( x, index ) => new                 {                     Color = (Color) x.GetValue( null ),                     Name = x.Name,                     Index = index,                 } );             this.DataContext = colors;         }      } } 

If you will ever think "I know that from somewhere" you should have a look at Jerry Nixon's blog :o)

Answers 4

VERSION 3: adding some logic just so not only ItemWidth and ItemHeight are a function of the parent's size, but also MaximumRowsOrColumns:

enter image description here

XAML:

<Page     x:Class="App1.MainPage"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:local="using:App1"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d">      <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"            SizeChanged="Grid1_SizeChanged">          <ScrollViewer>             <local:MyItemsControl ItemsSource="{Binding Data}">                 <ItemsControl.ItemsPanel>                     <ItemsPanelTemplate>                         <VariableSizedWrapGrid ItemWidth="{Binding MyWidth}"                                            ItemHeight="{Binding MyHeight}"                                            MaximumRowsOrColumns="{Binding MaxRowCol}"                                            Orientation="Horizontal"/>                     </ItemsPanelTemplate>                 </ItemsControl.ItemsPanel>                 <ItemsControl.ItemTemplate>                     <DataTemplate>                         <StackPanel VariableSizedWrapGrid.RowSpan="{Binding RowSpan}"                                  VariableSizedWrapGrid.ColumnSpan="{Binding ColSpan}"                                 BorderBrush="Gray"                                 BorderThickness="1"                                 Background="{Binding Color}"                                 Margin="5,5,5,5">                             <Image Source="{Binding Image}"                                Width="96"                                Height="96"                                HorizontalAlignment="Left"                                VerticalAlignment="Top"                                />                             <TextBlock FontWeight="Bold"                                         FontSize="16">                                 <Underline>                                     <Run Text="{Binding Headline}" />                                 </Underline>                                                         </TextBlock>                             <TextBlock FontSize="12"                                     TextWrapping="Wrap"                                    Text="{Binding Body}"/>                         </StackPanel>                     </DataTemplate>                 </ItemsControl.ItemTemplate>             </local:MyItemsControl>         </ScrollViewer>     </Grid> </Page> 

MainPage:

namespace App1 {     /// <summary>     /// An empty page that can be used on its own or navigated to within a Frame.     /// </summary>     public sealed partial class MainPage : Page     {         MyViewModel vm;          public MainPage()         {             this.InitializeComponent();              vm = new MyViewModel();             DataContext = vm;         }          private void Grid1_SizeChanged(object sender, SizeChangedEventArgs e)         {             // customize this logic to your needs              double curWidth = e.NewSize.Width;             double curHeight = e.NewSize.Height;              if (curWidth < 200)             {                 vm.MaxRowCol = 2;             }             else if (curWidth < 400)             {                 vm.MaxRowCol = 4;             }             else if (curWidth < 800)             {                 vm.MaxRowCol = 8;             }             else             {                 vm.MaxRowCol = 10;             }             vm.MyWidth = curWidth / vm.MaxRowCol;             vm.MyHeight = curHeight / vm.MaxRowCol;         }     } } 

ViewModel:

namespace App1 {     public class MyViewModel : INotifyPropertyChanged     {         public event PropertyChangedEventHandler PropertyChanged = delegate { };          public ObservableCollection<MyDataModel> Data { get; set; }          public MyViewModel()         {             Data = new ObservableCollection<MyDataModel>             {                 new MyDataModel { Color = "DarkRed", RowSpan = 3, ColSpan = 3, Headline = "Headline 1", Image = "ms-appx:///Assets/64-001.jpg", Body = "Lorem ipsum dolor sit amet, amet class elementum nunc ante." },                 new MyDataModel { Color = "DarkGreen", RowSpan = 4, ColSpan = 3, Headline = "Headline 2", Image = "ms-appx:///Assets/64-002.jpg", Body = "Tristique ullamcorper, nulla lacinia consectetuer."  },                 new MyDataModel { Color = "DarkRed", RowSpan = 3, ColSpan = 3, Headline = "Headline 3", Image = "ms-appx:///Assets/64-003.jpg", Body = "Rerum dui, hendrerit a id suscipit turpis lectus."  },                 new MyDataModel { Color = "DarkBlue", RowSpan = 4, ColSpan = 3, Headline = "Headline 4", Image = "ms-appx:///Assets/64-004.jpg", Body = "Lorem ipsum dolor sit amet, amet class elementum nunc ante."  },                 new MyDataModel { Color = "DarkOrange", RowSpan = 3, ColSpan = 3, Headline = "Headline 5", Image = "ms-appx:///Assets/64-005.jpg", Body = "Rerum dui, hendrerit a id suscipit turpis lectus."  },                 new MyDataModel { Color = "DarkGreen", RowSpan = 4, ColSpan = 3, Headline = "Headline 6", Image = "ms-appx:///Assets/64-006.jpg", Body = "Erat velit eligendi erat ante sapien arcu, wisi mi dictumst curabitur"  },                 new MyDataModel { Color = "DarkOrange", RowSpan = 3, ColSpan = 3, Headline = "Headline 7", Image = "ms-appx:///Assets/64-007.jpg", Body = "Tristique ullamcorper, nulla lacinia consectetuer."  },                 new MyDataModel { Color = "DarkRed", RowSpan = 4, ColSpan = 3, Headline = "Headline 8", Image = "ms-appx:///Assets/64-008.jpg", Body = "Lorem ipsum dolor sit amet, amet class elementum nunc ante."  },                 new MyDataModel { Color = "DarkRed", RowSpan = 3, ColSpan = 3, Headline = "Headline 9", Image = "ms-appx:///Assets/64-009.jpg", Body = "Mus quisque velit libero habitasse libero, nam etiam a ornare pellentesque."  },                 new MyDataModel { Color = "DarkBlue", RowSpan = 4, ColSpan = 3, Headline = "Headline 10", Image = "ms-appx:///Assets/64-010.jpg", Body = "Rerum dui, hendrerit a id suscipit turpis lectus."  },                 new MyDataModel { Color = "DarkGreen", RowSpan = 3, ColSpan = 3, Headline = "Headline 11", Image = "ms-appx:///Assets/64-011.jpg", Body = "Erat velit eligendi erat ante sapien arcu, wisi mi dictumst curabitur"  },                 new MyDataModel { Color = "DarkRed", RowSpan = 4, ColSpan = 3, Headline = "Headline 12", Image = "ms-appx:///Assets/64-012.jpg", Body = "Tristique ullamcorper, nulla lacinia consectetuer."  },             };         }          private double mywidth;         public double MyWidth         {             get { return mywidth; }             set             {                 if (value != mywidth)                 {                     mywidth = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MyWidth"));                 }             }         }         private double myheight;         public double MyHeight         {             get { return myheight; }             set             {                 if (value != myheight)                 {                     myheight = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MyHeight"));                 }             }         }         private double maxrowcol;         public double MaxRowCol         {             get { return maxrowcol; }             set             {                 if (value != maxrowcol)                 {                     maxrowcol = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MaxRowCol"));                 }             }         }     } } 

Simply bind ItemWidth and ItemHeight to a fraction of its parent's size:

enter image description here


VERSION 2: using dynamic grid items with ItemsControl (please see Note below for UWP Apps):

XAML:

<Page     x:Class="App1.MainPage"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:local="using:App1"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d">      <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"            SizeChanged="Grid1_SizeChanged">          <local:MyItemsControl ItemsSource="{Binding Data}">             <ItemsControl.ItemsPanel>                 <ItemsPanelTemplate>                     <VariableSizedWrapGrid ItemWidth="{Binding MyWidth}"                                            ItemHeight="{Binding MyHeight}"                                            MaximumRowsOrColumns="10"/>                 </ItemsPanelTemplate>             </ItemsControl.ItemsPanel>             <ItemsControl.ItemTemplate>                 <DataTemplate>                     <Rectangle Fill="{Binding Color}"                                     VariableSizedWrapGrid.RowSpan="{Binding RowSpan}"                                    VariableSizedWrapGrid.ColumnSpan="{Binding ColSpan}"                                    Margin="5,5,5,5"/>                 </DataTemplate>             </ItemsControl.ItemTemplate>         </local:MyItemsControl>     </Grid> </Page> 

MyItemsControl:

namespace App1 {     public sealed class MyItemsControl : ItemsControl     {         public MyItemsControl()         {             this.DefaultStyleKey = typeof(MyItemsControl);         }         protected override void PrepareContainerForItemOverride(DependencyObject element, object item)         {             var viewModel = item as ISpan;              element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, viewModel.ColSpan);             element.SetValue(VariableSizedWrapGrid.RowSpanProperty, viewModel.RowSpan);              base.PrepareContainerForItemOverride(element, item);         }     } } 

Generic.xaml:

<ResourceDictionary     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:local="using:App1">      <Style x:Key="BaseItemsControl" TargetType="ItemsControl">     </Style>      <Style TargetType="local:MyItemsControl" BasedOn="{StaticResource BaseItemsControl}">     </Style>  </ResourceDictionary> 

MyViewModel:

namespace App1 {     public class MyViewModel : INotifyPropertyChanged     {         public event PropertyChangedEventHandler PropertyChanged = delegate { };          public ObservableCollection<MyDataModel> Data { get; set; }          public MyViewModel()         {             Data = new ObservableCollection<MyDataModel>             {                 new MyDataModel { Color = "LightCoral", RowSpan = 2, ColSpan = 3 },                 new MyDataModel { Color = "LightGreen", RowSpan = 3, ColSpan = 3 },                 new MyDataModel { Color = "LightCoral", RowSpan = 1, ColSpan = 3 },                 new MyDataModel { Color = "LightBlue", RowSpan = 2, ColSpan = 3 },                 new MyDataModel { Color = "LightYellow", RowSpan = 2, ColSpan = 3 },                 new MyDataModel { Color = "LightGreen", RowSpan = 3, ColSpan = 4 },                 new MyDataModel { Color = "LightYellow", RowSpan = 4, ColSpan = 4 },                 new MyDataModel { Color = "LightGreen", RowSpan = 3, ColSpan = 4 },                 new MyDataModel { Color = "LightCoral", RowSpan = 2, ColSpan = 3 },                 new MyDataModel { Color = "LightBlue", RowSpan = 3, ColSpan = 3 },                 new MyDataModel { Color = "LightGreen", RowSpan = 3, ColSpan = 3 },                 new MyDataModel { Color = "LightCoral", RowSpan = 2, ColSpan = 3 },             };         }          private double mywidth;         public double MyWidth         {             get { return mywidth; }             set             {                 if (value != mywidth)                 {                     mywidth = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MyWidth"));                 }             }         }         private double myheight;         public double MyHeight         {             get { return myheight; }             set             {                 if (value != myheight)                 {                     myheight = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MyHeight"));                 }             }         }     } } 

ISpan:

namespace App1 {     public interface ISpan     {         double RowSpan { get; set; }         double ColSpan { get; set; }     } } 

NOTE: It was necessary to extend ItemsControl and override PrepareContainerForItemOverride() in order to get RowSpan and ColumnSpan bindings working. Attached properties VariableSizedWrapGrid.RowSpan and VariableSizedWrapGrid.ColumnSpan are swallowed (talking UWP app) when wrapped by an item container, as discussed in this article.


VERSION 1: using static grid items:

XAML:

<Page     x:Class="App1.MainPage"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:local="using:App1"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d">      <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"            SizeChanged="Grid1_SizeChanged">         <VariableSizedWrapGrid ItemWidth="{Binding MyWidth}"                                ItemHeight="{Binding MyHeight}"                                MaximumRowsOrColumns="10">          <Rectangle Fill="LightCoral" VariableSizedWrapGrid.RowSpan="2" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightGreen" VariableSizedWrapGrid.RowSpan="3" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightCoral" VariableSizedWrapGrid.RowSpan="1" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightBlue" VariableSizedWrapGrid.RowSpan="2" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightYellow" VariableSizedWrapGrid.RowSpan="2" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>          <Rectangle Fill="LightGreen" VariableSizedWrapGrid.RowSpan="3" VariableSizedWrapGrid.ColumnSpan="4" Margin="5,5,5,5"/>         <Rectangle Fill="LightYellow" VariableSizedWrapGrid.RowSpan="4" VariableSizedWrapGrid.ColumnSpan="4" Margin="5,5,5,5"/>         <Rectangle Fill="LightGreen" VariableSizedWrapGrid.RowSpan="3" VariableSizedWrapGrid.ColumnSpan="4" Margin="5,5,5,5"/>          <Rectangle Fill="LightCoral" VariableSizedWrapGrid.RowSpan="2" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightBlue" VariableSizedWrapGrid.RowSpan="3" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightGreen" VariableSizedWrapGrid.RowSpan="3" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>         <Rectangle Fill="LightCoral" VariableSizedWrapGrid.RowSpan="2" VariableSizedWrapGrid.ColumnSpan="3" Margin="5,5,5,5"/>          </VariableSizedWrapGrid>     </Grid> </Page> 

MainPage:

namespace App1 {     /// <summary>     /// An empty page that can be used on its own or navigated to within a Frame.     /// </summary>     public sealed partial class MainPage : Page     {         MyViewModel vm;          public MainPage()         {             this.InitializeComponent();              vm = new MyViewModel();             DataContext = vm;         }          private void Grid1_SizeChanged(object sender, SizeChangedEventArgs e)         {             vm.MyWidth = e.NewSize.Width / 10;             vm.MyHeight = e.NewSize.Height / 10;         }     } } 

ViewModel:

namespace App1 {     public class MyViewModel : INotifyPropertyChanged     {         public event PropertyChangedEventHandler PropertyChanged = delegate { };          private double mywidth;         public double MyWidth         {             get { return mywidth; }             set             {                 if (value != mywidth)                 {                     mywidth = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MyWidth"));                 }             }         }         private double myheight;         public double MyHeight         {             get { return myheight; }             set             {                 if (value != myheight)                 {                     myheight = value;                     PropertyChanged(this, new PropertyChangedEventArgs("MyHeight"));                 }             }         }     } } 
Read More