I work on the front end of our app, configuring the UI. Our app originally had a ListView using Xamarin Community Toolkit's EventToCommandBehavior with custom ViewCells to facilitate the search. We set up custom renderers to change the ViewCell's background color. However, when I moved over to the Mac, we discovered that none of that worked with iOS; the cell background would not change.
At this point, I switched to a CollectionView with a TapGestureRecognizer on the grid using VisualStateManager to change the background color. Since then, I can either get the grid selection to highlight without the command enabling our buttons or the command to fire which enables the buttons, but the grid selection will not highlight. Simply put, I either get the command or the event but have been unable to get them working together. This is also a problem on our store page; the IAP's never highlighted before the purchase confirmation popped up. We have been experiencing this issue from the start and never noticed.
Here is the relevant XAML:
<!--Faction Search Results-->
<Frame Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="6" BackgroundColor="Black" BorderColor="White" CornerRadius="5">
<CollectionView ItemsSource="{Binding FactionItems}"
BackgroundColor="Transparent">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid x:DataType="Data:Faction" BackgroundColor="Black">
<Grid.GestureRecognizers>
<TapGestureRecognizer
NumberOfTapsRequired="1"
Command="{Binding Source={RelativeSource AncestorType={x:Type local:FactionTopPageViewModel}}, Path=ItemTapped}"
CommandParameter="{Binding .}">
</TapGestureRecognizer>
</Grid.GestureRecognizers>
<Grid.RowDefinitions>
<RowDefinition Height="{markups:OnScreenSize DefaultSize='12', iPod='20', iPhoneSE='20', iPhoneXR='20', iPhoneX='20', iPhone13='25', iPhone7p='25', iPhone11pm='25', iPhone13pm='16',
iPadMini='35', iPad9p7='35', iPad='35', iPadAir='35', iPad11='35', iPad12p9='40', Nexus1='20', NexusR='25', Nexus7R='30', Pixel2R='25', Pixel3R='25', GalaxyS8='25', Nexus6P='25', Pixel3XL='25', PixelC='40'}" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Padding="10,5" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4" Text="{Binding FactionName}" HorizontalOptions="Start" VerticalTextAlignment="End" FontAttributes="Bold"
FontSize="{markups:OnScreenSize DefaultSize='12', iPod='15', iPhoneSE='15', iPhoneXR='18', iPhoneX='19', iPhone13='19', iPhone7p='19', iPhone11pm='19', iPhone13pm='16',
iPadMini='30', iPad9p7='30', iPad='32', iPadAir='32', iPad11='34', iPad12p9='34', Nexus1='14', NexusR='14', Nexus7R='22', Pixel2R='20', Pixel3R='20', GalaxyS8='20', Nexus6P='18', Pixel3XL='18', PixelC='34'}" />
<Label Padding="0,5" Grid.Row="0" Grid.Column="4" Grid.ColumnSpan="2" Text="{Binding NumberMembersString}" HorizontalOptions="Center" VerticalTextAlignment="End" FontAttributes="Bold"
FontSize="{markups:OnScreenSize DefaultSize='12', iPod='15', iPhoneSE='15', iPhoneXR='18', iPhoneX='19', iPhone13='19', iPhone7p='19', iPhone11pm='19', iPhone13pm='16',
iPadMini='30', iPad9p7='30', iPad='32', iPadAir='32', iPad11='34', iPad12p9='34', Nexus1='14', NexusR='14', Nexus7R='22', Pixel2R='20', Pixel3R='20', GalaxyS8='20', Nexus6P='18', Pixel3XL='18', PixelC='34'}"/>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal"></VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="#ae00ff"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Relevant code from the ViewModel:
public Command<Faction> ItemTapped { get; }
public FactionTopPageViewModel()
{
ItemTapped = new Command<Faction>(OnItemSelected);
}
private void OnItemSelected(Faction faction)
{
if (faction == null)
{
SelectedItem = null;
DisableFactionButtons();
return;
}
EnableFactionButtons();
SelectedItem = faction;
}
This results in our buttons enabled at the bottom of the page, but the faction (essentially a team) is not being highlighted in the CollectionView, so the user does not receive confirmation of selecting the proper faction.
If I remove the tapgesture and work through the CollectionView commands setting the SelectionMode="Single", SelectionChangedCommand={Binding IsTapped}, and SelectionChangedCommandParameter={Binding .} then the selected Faction highlights without enabling any buttons. These issues are not platform-specific, like the ListView ViewCell background.
I have been working on this longer than I care to mention, as it seems like I have not wrapped my head around some relatively simple concept. Any help would be greatly appreciated, this issue is holding up the next release of our app.
Related
I am trying to customize the selection color of a cell in a CollectionView but no matter how I try it, it's always an ugly grey.
I want my item template to have rounded corners, but when I select an item the I see ugly square grey corners behind it, as in this image:
Here's my current XAML:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Tests.CollectionViewTest">
<ContentView.Content>
<CollectionView
x:Name="collectionView"
Margin="15,0"
ItemSizingStrategy="MeasureFirstItem"
Grid.Row="1"
Grid.RowSpan="2"
VerticalScrollBarVisibility="Never"
BackgroundColor="Transparent"
SelectionMode="Multiple"
HorizontalOptions="Center"
VerticalOptions="Center"
>
<CollectionView.ItemsLayout>
<GridItemsLayout
Orientation="Vertical"
HorizontalItemSpacing="1"
VerticalItemSpacing="1"
Span="3" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame
x:Name="selectionFrame"
CornerRadius="18"
BackgroundColor="Transparent"
Padding="0"
HasShadow="False"
IsClippedToBounds="True"
BorderColor="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup
Name="CommonStates">
<VisualState
Name="Normal" />
<VisualState
Name="Focused">
<VisualState.Setters>
<Setter
Property="BackgroundColor"
Value="Transparent" />
</VisualState.Setters>
</VisualState>
<VisualState
Name="Selected">
<VisualState.Setters>
<Setter
Property="BackgroundColor"
Value="#e25fc4" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<StackLayout
BackgroundColor="#f7f0f6"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Orientation="Vertical"
Padding="8,0,8,10"
Margin="10"
Spacing="0"
HeightRequest="100">
<Label
Padding="10"
x:Name="ServiceName"
BackgroundColor="Transparent"
Text="Some Text"
HorizontalTextAlignment="Center"
TextColor="HotPink"
FontSize="Micro"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="End" />
<Label
BackgroundColor="Transparent"
Text="Some More Text"
HorizontalTextAlignment="Center"
TextColor="HotPink"
FontSize="Micro"
HorizontalOptions="Center"
VerticalOptions="Start" />
</StackLayout>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentView.Content>
</ContentView>
And my code-behind:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms;
namespace Tests
{
public partial class CollectionViewTest : ContentView
{
public CollectionViewTest()
{
InitializeComponent();
collectionView.ItemsSource = new ObservableCollection<string>()
{
"", "", "", "", "", "", "", "", "", "", "", "", "", ""
};
}
}
}
I've tried other ways of doing this too, but nothing worked.
Is there a way to do it, or is this just a bug with CollectionView?
I found a kludgey solution, and in the absence of one that works the right way, it will have to do.
Set selection behavior in the CollectionView to none.
Put a tapGestureRecognizer into the itemTemplate
To simulate selection states, in the event handler for the tapGestureRecognizer, cast the sender to a Frame (or whatever element you attached the gesture recognizer to) and turn the frame border on or off (or do whatever you need to for your own custom selected-state appearance).
Manually handle whatever would normally be triggered by the CollectionView in response to selections. In other words, if you can select multiple items, you might be tracking the selected items in a separate list, and you will now have to do that from inside the tapGestureRecognizer.
It’s wrong but it works and sometimes that’s how you gotta do.
I start again to try to make it work, now i have a Frame in a StackLayout. And not a the other way around. But no luck is see , now there are no corners around the selected item.Sorry but i cannot make it to work.
I am trying to achieve the effect, cross-platform(ios, android and uwp), as shown in the image below:
Clicking "More" normally would open a page, as normal behaviour for a tab bar item. Not sure how to override that behaviour and reveal the sliding master page instead. To the left of the "More" tab bar item, theres another tab bar item, when clicked it refreshes the data on (or reloads) the MainPage.
SettingsPage.xaml (master page, the sliding settings page)
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject.Classes"
xmlns:views="clr-namespace:MyProject.Views"
x:Class="MyProject.Views.SettingsMasterPage"
IconImageSource="menu.png"
Padding="0,40,0,0"
Title="Menu">
<StackLayout>
<ListView x:Name="listView" x:FieldModifier="public">
<ListView.ItemsSource>
<x:Array Type="{x:Type local:MasterPageItem}">
<local:MasterPageItem Title="Settings Link 1" />
<local:MasterPageItem Title="Settings Link 2" />
<local:MasterPageItem Title="Settings Link 3" />
</x:Array>
</ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding IconSource}" />
<Label Grid.Column="1" Text="{Binding Title}" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
MyTabbedPage.xaml
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
xmlns:views="clr-namespace:MyProject.Views;assembly=MyProject"
x:Class="Xamarin.Sigma01.Views.LoggerDetectionTabbedPage"
android:TabbedPage.ToolbarPlacement="Bottom"
BarBackgroundColor="White"
SelectedTabColor="Black"
BarTextColor="Black">
<TabbedPage.Children>
<views:MainPage IconImageSource="tab_icon_mainpage.png" />
<!-- second link should be the sandwhich button that brings up the settings page -->
</TabbedPage.Children>
</TabbedPage>
MainPage.xaml (the main page, navigated to by the left TabBar link icon, to the left of the sandwhich icon with title "More")
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to the Main page!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
An easy way I can achieve the effect is to use Shell. It's released for months and just check your VS version for the correct template.
Create a new Xamarin.Forms project using VS2019.
You can use Shell out of the box if you can see the following screen.
Find "ItemsPage.xaml" in the Views folder.
Add one line in the ContentPage at the top
<ContentPage
...
Shell.TabBarIsVisible="False">
Add a StackLayout to contain the existing CollectionView and add your bottom buttons.
<RefreshView ...>
<!-- new StackLayout -->
<StackLayout>
<CollectionView ..... />
<!-- new Buttons -->
<StackLayout
HeightRequest="52"
Orientation="Horizontal"
BackgroundColor="#2196F3"
Visual="Material">
<Button
WidthRequest="200"
BackgroundColor="Transparent"
Text="Refresh"
Command="{Binding LoadItemsCommand}" />
<Button
BackgroundColor="Transparent"
Text="More"
Clicked="Button_Clicked" />
</StackLayout>
</StackLayout>
Go to "ItemsPage.xaml.cs" to complete the button event, add a method:
private void Button_Clicked(object sender, EventArgs e)
{
Shell.Current.FlyoutIsPresented = true;
}
Set startup project and deploy, check the effect and play around.
Additionally, in the latest Xamarin.Forms, UWP Shell is an experimental feature, and so does in XF 5.0. But the flyout things will probably work fine (not too sure about this).
An alternative, following the idea from #Shaw, but without Shell is to use the good old MasterDetail Page (which supports UWP) and add two buttons at the bottom to provide the "More" and "Refresh" functionality.
If this sounds like a good option for you, keep reading:
Add a Master-Detail Page to your Solution
On Visual Studio 2019 adding a Master-Detail to your solution is pretty straight forward. You only need to right click the Xamarin.Forms Project in the Solution Explorer and go to Add -> New Item (or simply use the shortcut Ctrl+Shift+A):
in the window that appears, select Master-Detail Page, give it a cool name (MasterDetailPage1 in this example!) and click Add:
By doing this you successfully have added a Master Detail to your solution. Now just go to App and set MainPage to it as follows:
MainPage = new MasterDetailPage1();
Add the bottom buttons
Now we want two buttons at the bottom of our Detail page. This is simply done by adding a stack of two buttons that locate at the end. Our newly added MasterDetailPage1Detail.xaml will then look like:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MasterTabRefresh.MasterDetailPage1Detail"
Title="Detail">
<StackLayout>
<Label Text="This is a detail page. To get the 'triple' line icon on each platform add a icon to each platform and update the 'Master' page with an Icon that references it."
Padding="10"/>
<StackLayout Orientation="Horizontal"
VerticalOptions="EndAndExpand"
Spacing="0">
<Button BackgroundColor="CornflowerBlue"
Text="Refresh"
TextColor="White"
CornerRadius="0"
HorizontalOptions="FillAndExpand"/>
<Button BackgroundColor="CornflowerBlue"
Text="More"
TextColor="White"
CornerRadius="0"
HorizontalOptions="FillAndExpand"
Clicked="MoreClicked"/>
</StackLayout>
</StackLayout>
</ContentPage>
which should look like:
And in the code behind (MasterDetailPage1Detail.xaml.cs ) we add the "More" functionality:
private void MoreClicked(object sender, EventArgs e)
{
((MasterDetailPage)Application.Current.MainPage).IsPresented = !((MasterDetailPage)Application.Current.MainPage).IsPresented;
}
Add a nice X (close) button to your menu/master
This could be achieved by adding a label with an "X" at the top right of the menu.
Simply modify your MasterDetailPage1Master.xaml to look like (note Label at Column 2 Row 0!)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MasterTabRefresh.MasterDetailPage1Master"
Title="Master">
<StackLayout>
<ListView x:Name="MenuItemsListView"
SeparatorVisibility="None"
HasUnevenRows="true"
ItemsSource="{Binding MenuItems}">
<ListView.Header>
<Grid BackgroundColor="#03A9F4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="80"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="10"/>
</Grid.RowDefinitions>
<Label Grid.Column="2"
Grid.Row="0"
Text="X"
FontAttributes="Bold"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="X_Tapped"/>
</Label.GestureRecognizers>
</Label>
<Label
Grid.Column="1"
Grid.Row="2"
Text="My wonderful App"
Style="{DynamicResource SubtitleStyle}"/>
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="15,10" HorizontalOptions="FillAndExpand">
<Label VerticalOptions="FillAndExpand"
VerticalTextAlignment="Center"
Text="{Binding Title}"
FontSize="24"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
Which should look like this:
And then add the "Close" functionality to that "X" Label in the code behind (MasterDetailPage1Master.xaml):
private void X_Tapped(object sender, EventArgs e)
{
((MasterDetailPage)Application.Current.MainPage).IsPresented = false;
}
And that is it! This should get you going. Happy coding!
I have a layout with a few elements that get layout binding:
<Grid Grid.Column="1" RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label
HorizontalOptions="Start"
VerticalOptions="End"
FontFamily="arial"
FontSize="18"
TextColor="#151515"
FontAttributes="Bold"
Grid.Row="0"
Text="{Binding title}"
/>
<Label
HorizontalOptions="Start"
VerticalOptions="Start"
FontFamily="arial"
FontSize="13"
TextColor="#151515"
Grid.Row="1"
Text="{Binding subtitle}"
/>
</Grid>
So I am giving it mulitple objects with different contents set on a variable with the same name and the result is that all layout get inflated with different contents. That works fine.
However, there is a little notification icon to the right of each layout:
<Grid Grid.Column="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ImageButton
VerticalOptions="Center"
HorizontalOptions="Center"
Source="img_notify.png"
Grid.Column="1"/>
<!-- BackgroundColor="#00000000"-->
<Label
HorizontalOptions="Center"
VerticalOptions="Center"
FontFamily="arial"
FontSize="18"
TextColor="#ffffff"
FontAttributes="Bold"
Grid.Column="1"
Text="!"
/>
</Grid>
It looks like this:
Now, once the user clicked on one of those elements, the notify button is just supposed to dissapear, since the user has already seen it.
Therefor I set up a database that stores the name and the subtitle of the ad if clicked and the next time the list becomes visible, each object is checked:
private async void ReturnDataBaseToListAndUpdateNotifyButton(List<ListView_Matches> contentOfListView)
{
List<db_MatchesNotify_Type> contentOfDatabase = await Database.GetIDsAlreadyClickedOn();
foreach (var o in contentOfListView) // for each match in our list...
{
for(var i = 0; i < contentOfDatabase.Count; i++) //... check every object in our database if they match
{
if (o.title == contentOfDatabase[i].titleOfAd && o.userID == contentOfDatabase[i].userID) // check if matches then delete icon
{
}
}
}
}
.. by using nested looping.
Now I know that my database is working fine and that my logic is OK, but u see that in within the last "if" statement, nothing is happening since I dont know how to adress the notification button now.
Bascially, in within the IF (if a match between the data from the list and the data from the database is found) i would need to set the notifybutton to invisible.
But 1.) I cannot access the object by name since the property from a list is not transported to the class but most:
2.) even if I just set it to invisible then ALL the notifybuttons in my list would become insivible. Ofc I only want this particular object on which a match was found to become invisible.
I need to access the layout that has been inflated individually and decided for each new button now wheater it is visible or not.
How can I achieve that?
Thank you!
You do it the same way you have set your Labels' bindings. The idea is that this ImageButton will always be in the layout and you will simply toggle its IsVisible property with a binding.
<ImageButton
IsVisible="{Binding IsNotifyIconVisible}"
VerticalOptions="Center"
HorizontalOptions="Center"
Source="img_notify.png"
Grid.Column="1"/>
You haven't specified anywhere what your collection's binding context is, but I assume it is some sort of an IEnumerable<YourItemViewModel>. In YourItemViewModel.cs, besides title & subtitle, you will have a property IsNotifyIconVisible and that way you will be able set it to true/false on demand.
I am creating new instance of grid object which have two labels as following.
<Grid x:Name="Grid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="30*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Label x:Name="Label1" Text="Label1" Grid.Column="0" Grid.Row="0"></Label>
<Label x:Name="Label2" Text="Label2" Grid.Column="1" Grid.Row="0"></Label>
</Grid>
I am using Activator.CreateInstance method as given below:
Grid ClonedView =(Grid) Activator.CreateInstance(Grid.GetType());
foreach (PropertyInfo propertyInfo in Grid.GetType().GetProperties())
{
if (propertyInfo.CanRead && propertyInfo.CanWrite )
{
object PropertyValue = propertyInfo.GetValue(Grid, null);
propertyInfo.SetValue(ClonedView, PropertyValue);
}
}
When I use this ClonedView in my page, it Cloned Grid don't understand that Label2 should appear in second column of grid. I did a lot of research on it but could not find any solution. Please let me know if anybody has any solutions.
thanks
They way you're thinking about this, feels very JavaScript like to me. You want to create a deep copy by copying all properties. However the Xamarin objects are way too complex for something like this (even if you where able to do a deep copy, Bindings for example won't work with simple copying).
So instead of making a single Grid object and trying to create copies of it, another way of looking at it would be "I want to define a template, and then create multiple instances according to that template". For this Xamarin has the DataTemplate class, which enables us to do something like this in xaml:
<ContentPage>
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="MyGridTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70*"></ColumnDefinition>
<ColumnDefinition Width="30*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Label Text="Label1" Grid.Column="0" Grid.Row="0"></Label>
<Label Text="Label2" Grid.Column="1" Grid.Row="0"></Label>
</Grid>
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
<Button Text="Add Grid" Clicked="AddGridClicked">
</Button>
<StackLayout x:Name="GridHolder">
<StackLayout>
<ContentPage>
And in our code behind we can implement AddGridClicked like this:
private void AddGridClicked(object sender, EventArgs e)
{
var myGridTemplate = (DataTemplate) Resources["MyGridTemplate"];
GridHolder.Children.Add((View)myGridTemplate.CreateContent());
}
Now the downside is that you need to define a DataTemplate instead of just pointing at an object and saying getting a copy. Also keep in mind that x:Name of a View in the DataTemplate can't be accessed in code behind of your page, but with a good Xamarin setup that should not be needed. The upside is that this works, complete with possible bindings, so you're allowed to define a Label in your grid like this:
<Label Text="{Binding Name}" Grid.Column="0" Grid.Row="0"></Label>
And then you can give each instance if your templated Grid a different BindingContext to bind different data to it's views.
Hope this helps
I have a custom Expander that I've created as a template:
<local:MultiplyConverter x:Key="multiplyConverter" />
<ControlTemplate x:Key="AnimatedExpander" TargetType="{x:Type Expander}">
<DockPanel>
<ToggleButton x:Name="ExpanderButton" DockPanel.Dock="Top" Template="{StaticResource ExpanderButton}" Content="{TemplateBinding Header}" IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" OverridesDefaultStyle="True">
</ToggleButton>
<ScrollViewer x:Name="ExpanderContentScrollView" DockPanel.Dock="Bottom" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Bottom">
<ScrollViewer.Tag>
<sys:Double>0.0</sys:Double>
</ScrollViewer.Tag>
<ScrollViewer.Height>
<MultiBinding Converter="{StaticResource multiplyConverter}">
<Binding Path="ActualHeight" ElementName="ExpanderContent"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</ScrollViewer.Height>
<ContentPresenter x:Name="ExpanderContent" ContentSource="Content" />
</ScrollViewer>
</DockPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsExpanded" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="ExpanderContentScrollView" Storyboard.TargetProperty="Tag" To="1" Duration="0:0:0.3">
<DoubleAnimation.EasingFunction>
<CubicEase EasingMode="EaseOut"/>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="ExpanderContentScrollView" Storyboard.TargetProperty="Tag" To="0" Duration="0:0:0.3">
<DoubleAnimation.EasingFunction>
<CubicEase EasingMode="EaseOut"/>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
When I actually go to instantiate the Expander inside a grid, the code looks like this:
<Expander Template="{StaticResource AnimatedExpander}" ExpandDirection="Down" OverridesDefaultStyle="True" FontSize="11.0" Foreground="#CC000000" Header="Export Options" HorizontalAlignment="Stretch" VerticalAlignment="Bottom">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Border Grid.Column="0" CornerRadius="0" Background="Transparent" Margin="10,0,10,0" BorderBrush="#FFAAAAAA" BorderThickness="0,0,0,0.5">
<ComboBox Grid.Column="0" ItemsSource="{Binding CurrentSlicerManager.Exporters}" DisplayMemberPath="Name" SelectedItem="{Binding CurrentSlicerManager.SelectedExporter, Mode=TwoWay}" Grid.Row="0" Margin="0,0,0,10"></ComboBox>
</Border>
<ContentControl Content="{Binding CurrentSlicerManager}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"></ContentControl>
</Grid>
</Expander>
As you can see, I've bound the content inside the Expander to a ContentControl. The ContentControl uses a DataTemplate to determine which .xaml I should load into the Expander. So, I have two DataTemplates that look like this:
<DataTemplate DataType="{x:Type MLC:MLRasterSlicerManager}">
<local:MLRasterSlicerExportSettings></local:MLRasterSlicerExportSettings>
</DataTemplate>
<DataTemplate DataType="{x:Type MLC:MLVectorSlicerManager}">
<local:MLVectorSlicerExportSettings></local:MLVectorSlicerExportSettings>
</DataTemplate>
So, I have two .xaml files (MLRasterSlicerExportSettings and MLVectorSlicerExportSettings) which get loaded... and this works fine. The issue is that the height of these two interfaces are different. When, I change the combobox which controls which file to load into the expander, I would expect the expander to automatically resize itself. And, this does happen when it first loads the expander with the smaller height and then I switch it to load the one with the larger height value... the expander does resize itself to accommodate the larger file... but if I switch it back to the smaller one, then it never resizes to the appropriate height. It just remains the same height as the largest file. Can anyone recommend how to get this expander to automatically resize to the size of the content?