UWPCommunityToolkit's PrintHelper produce blank output - printing

I have my code below, basically to print out an image.
private async void imageControl_PrintButtonClick(object sender, RoutedEventArgs e)
{
var createBitmapTask = Task.Run(async () =>
{
var stream = await provider.OpenEntryAsRandomAccessStreamAsync(currentImageFile);
var decoder = await BitmapDecoder.CreateAsync(stream);
return await decoder.GetSoftwareBitmapAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied);
});
var printHelper = new PrintHelper(printPanel);
printHelper.OnPreviewPagesCreated += PrintHelper_OnPreviewPagesCreated;
printPanel.Opacity = 1.0;
var source = new SoftwareBitmapSource();
var bitmap = await createBitmapTask;
await source.SetBitmapAsync(bitmap);
printImage.Source = source;
printFileName.Text = "Hello";
printImage.Height = bitmap.PixelHeight;
printImage.Width = bitmap.PixelWidth;
await printHelper.ShowPrintUIAsync("ZipPicView - " + currentImageFile.ExtractFilename(), true);
printPanel.Opacity = 0;
}
private void PrintHelper_OnPreviewPagesCreated(List<FrameworkElement> obj)
{
ContentDialog dialog = new ContentDialog();
}
However, the print preview shows an empty page. When I print it out, the printer does nothing.
I've tried changing the opacity of the printPanel (which is a Grid object) to non-zero, and the image does display on the screen. Still, the print has nothing on the output page.
I did notice that, on the OnPreviewPagesCreated, its obj parameter has a new object everytime it's called. The first call has one object with both Width and Height as NaN. My guess is because the container has no size, it cannot determine the content size.
Below is the XAML file.
<Page x:Name="page"
x:Class="ZipPicViewUWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ZipPicViewUWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:behaviors="using:Microsoft.Toolkit.Uwp.UI.Animations.Behaviors"
mc:Ignorable="d" KeyUp="page_KeyUp" Loaded="page_Loaded" SizeChanged="page_SizeChanged">
<Canvas x:Name="canvas" SizeChanged="canvas_SizeChanged">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Height="1019" Width="1920">
<Grid x:Name="printPanel" Opacity="0">
<StackPanel x:Name="printContent"
Margin="0,0"
Orientation="Vertical">
<TextBlock x:Name="printFileName" />
<Image x:Name="printImage"
Stretch="Fill" />
</StackPanel>
</Grid>
<SplitView x:Name="splitView" DisplayMode="CompactOverlay" PanePlacement="Left" CompactPaneLength="50" OpenPaneLength="300">
<SplitView.Content>
<GridView x:Name="thumbnailGrid" />
</SplitView.Content>
<SplitView.Pane>
<Grid Background="{StaticResource SidebarBackground}">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<Button x:Name="subFolderButton" Width="50" Height="50" Background="Transparent" Click="subFolderButton_Click">
<SymbolIcon Symbol="List" />
</Button>
<TextBlock VerticalAlignment="Center" Margin="0,15">Folders</TextBlock>
</StackPanel>
<ScrollViewer Grid.Row="1">
<ListView x:Name="subFolderListCtrl" SelectionChanged="subFolderList_SelectionChanged" DataFetchSize="2" Margin="-10,0,0,0" />
</ScrollViewer>
<ProgressRing x:Name="thumbProgress" Height="30" Width="30" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="2" Margin="10,0,0,10" />
</Grid>
</SplitView.Pane>
</SplitView>
<interactivity:Interaction.Behaviors>
<behaviors:Blur x:Name="BlurBehavior" Duration="500" AutomaticallyStart="False" />
</interactivity:Interaction.Behaviors>
</Grid>
<Border x:Name="imageBorder" Visibility="Collapsed">
<Image x:Name="image" ManipulationMode="TranslateX" ManipulationCompleted="image_ManipulationCompleted" Tapped="image_Tapped">
<interactivity:Interaction.Behaviors>
<behaviors:Blur x:Name="ImageTransitionBehavior" Duration="500" AutomaticallyStart="False" />
</interactivity:Interaction.Behaviors>
</Image>
</Border>
<local:ViewerControl x:Name="imageControl" Visibility="Collapsed" CloseButtonClick="imageControl_CloseButtonClick" NextButtonClick="imageControl_NextButtonClick" PrevButtonClick="imageControl_PrevButtonClick" SaveButtonClick="imageControl_SaveButtonClick" PrintButtonClick="imageControl_PrintButtonClick" />
<Border x:Name="loadingBorder" Visibility="Collapsed">
<ProgressRing IsActive="True" Width="100" Height="100" />
</Border>
</Canvas>
<Page.TopAppBar>
<CommandBar VerticalContentAlignment="Center" VerticalAlignment="Center">
<CommandBar.Content>
<TextBlock Margin="10,0,0,0" x:Name="filenameTextBlock" Text="<None>" UseLayoutRounding="True" />
</CommandBar.Content>
<AppBarToggleButton x:Name="fullscreenButton" Icon="FullScreen" Label="FullScreen" Checked="fullscreenButton_Checked" Unchecked="fullscreenButton_Unchecked" />
<AppBarSeparator />
<AppBarButton x:Name="openFileButton" Icon="OpenFile" Label="Open File" Click="openFileButton_Click" />
<AppBarButton x:Name="openFolderButton" Icon="Folder" Label="Open Folder" Click="openFolderButton_Click" />
</CommandBar>
</Page.TopAppBar>
</Page>
And the source code is here : https://github.com/wutipong/ZipPicViewCS/tree/master/ZipPicViewUWP

Related

Xaml controls don't show up

I have a Xamarin.Forms app with FreshMvvm. Some of its users experience a problem on their iPhones. A page comes up empty. Here is how the page would look with a simulated exception:
All static xaml stuff is there, including labels. But our customers see this instead:
In the ScrollView, only the BoxViews with height = 1 that make those horizontal lines, are there. And no labels.
Here is my xaml:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="LATICRETE_MobileApp.Pages.CoverageCalculator.CoverageCalculatorResultsPage"
ControlTemplate="{StaticResource MainPageTemplate}"
xmlns:controls="clr-namespace:LATICRETE_MobileApp.Controls"
Title="Coverage Results" >
<ContentPage.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="4*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ScrollView Grid.Row="0">
<StackLayout Margin="30">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="1" />
<RowDefinition Height="Auto" />
<RowDefinition Height="1" />
<RowDefinition Height="Auto" />
<RowDefinition Height="1" />
<RowDefinition Height="Auto" />
<RowDefinition Height="22" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="Tile Size:" FontAttributes="Bold" Grid.Row="0" Grid.Column="0" />
<Label Text="Tile Thickness:" FontAttributes="Bold" Grid.Row="2" Grid.Column="0" />
<Label Text="Joint Size:" FontAttributes="Bold" Grid.Row="4" Grid.Column="0" />
<Label Text="Trowel Size:" FontAttributes="Bold" Grid.Row="6" Grid.Column="0" />
<Label Text="{Binding TileSize}" Grid.Row="0" Grid.Column="1" />
<BoxView BackgroundColor="Gray" Grid.Row="1" Grid.ColumnSpan="2" />
<Label Text="{Binding TileThickness}" Grid.Row="2" Grid.Column="1" />
<BoxView BackgroundColor="Gray" Grid.Row="3" Grid.ColumnSpan="2" />
<Label Text="{Binding JointSize}" Grid.Row="4" Grid.Column="1" />
<BoxView BackgroundColor="Gray" Grid.Row="5" Grid.ColumnSpan="2" />
<Label Text="{Binding TrowelSize}" Grid.Row="6" Grid.Column="1" />
<BoxView BackgroundColor="{StaticResource LaticreteColor}" Margin="0,10,0,10" Grid.Row="7" Grid.ColumnSpan="2" />
</Grid>
<Label Text="{Binding Adhesive}" FontAttributes="Bold" />
<Label Text="{Binding AdhesiveCoverage}" />
<BoxView BackgroundColor="Gray" HeightRequest="1" />
<Label Text="{Binding Grout}" FontAttributes="Bold" />
<Label Text="{Binding GroutCoverage}" />
<BoxView BackgroundColor="Gray" HeightRequest="1" />
<Label Style="{StaticResource LabelParagraphStyle}" Text="*Calculated coverage indicated is approximate, based on nominal tile size and is provided for purposes of estimation only." />
<Label Style="{StaticResource LabelParagraphStyle}" Text="Actual grout coverage will vary depending on jobsite conditions, actual tile size and installed grout joint size. Use of sufficient thin-set reduces grout requirement." />
<Label Style="{StaticResource LabelParagraphStyle}" Text="Add 10% to coverage estimates for waste, spillage and clean-up. Add 10%-15% to grout coverage estimate when grouting unglazed quarry tile." />
<Button
Text="{Binding ButtonShareText}"
Command="{Binding ShareCommand}"
Style="{StaticResource ButtonStyle}"
FontSize="Large"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ScrollView>
<controls:Toolbar
ButtonCalculatorIcon="{Binding ButtonCalculatorIcon}"
ButtonDistributorLocatorIcon="{Binding ButtonDistributorLocatorIcon}"
ButtonScanQRCodeIcon="{Binding ButtonScanQRCodeIcon}"
ButtonVideoCallIcon="{Binding ButtonVideoCallIcon}"
ButtonMoreIcon="{Binding ButtonMoreIcon}"
CalculatorCommand="{Binding CalculatorCommand}"
DistributorsLocatorCommand="{Binding DistributorsLocatorCommand}"
ScanQRCommand="{Binding ScanQRCommand}"
VideoCallCommand="{Binding VideoCallCommand}"
MoreFeaturesCommand="{Binding MoreFeaturesCommand}"
ShowVideoChat="{Binding ShowVideoChat}"
ControlTemplate="{StaticResource ToolbarTemplate}"
Grid.Row="1" />
</Grid>
</ContentPage.Content>
On App Center Diagnostics, I could see exceptions like this:
I don't know if this causes our issue, but that is the only thing I could find.
Also, on the same iPhone models some users have this issue, and others don't. I personally could not reproduce it on my phones.
ADDED:
The code-behind constructor and the pagemodel constructor contain almost nothing:
public CoverageCalculatorResultsPage ()
{
InitializeComponent ();
}
...
public CoverageCalculatorResultsPageModel()
{
ScreenName = "Coverage Results";
ShareCommand = new Command(async () => await Share());
}
Pagemodel's Init():
public override void Init(object initData)
{
try
{
base.Init(initData);
throw new Exception("Test Exception: remove when done");
_previousModel = (CoverageCalculatorPageModel)initData;
// Standard units
string lengthUnits = "\"";
string coverageUnits = " Ft²";
double tileWidth = Convert.ToDouble(_previousModel.TileWidth, CultureInfo.InvariantCulture);
double tileHeight = Convert.ToDouble(_previousModel.TileHeight, CultureInfo.InvariantCulture);
double jointWidth = Convert.ToDouble(_previousModel.SelectedJointSize.Key, CultureInfo.InvariantCulture);
double tileThickness = Convert.ToDouble(_previousModel.SelectedTileThickness.Key, CultureInfo.InvariantCulture);
if (_previousModel.SelectedUnit.Code == UnitCode.Metric)
{
lengthUnits = "mm";
coverageUnits = "M²";
// Convert to standard units
tileWidth /= 25.4;
tileHeight /= 25.4;
}
// Perform adhesive calculation
// Official formula is: Coverage (Sq Ft)/Unit = (coverage_cuInPerUnit/((Trowel_Height * 0.707108)/2)) * 0.0069444
double cuInPerUnit = _previousModel.SelectedAdhesive.Coverage;
double trowelHeight = Convert.ToDouble(_previousModel.SelectedTrowelSize.Key, CultureInfo.InvariantCulture);
double adhesiveCoverage = (cuInPerUnit / ((trowelHeight * 0.559) / 2)) * 0.0069444;
// Perform grout calculation
// Official formula is: Coverage (Sq Ft)/Unit = coverage_cuInPerUnit/((Tile_Width+Tile_Height+Joint_Width)*Tile_Thickness*Joint_Width*(144/((Tile_Width+Joint_Width)*(Tile_Height+Joint_Width))))
cuInPerUnit = _previousModel.SelectedGrout.Coverage;
double groutCoverage = cuInPerUnit / ((tileWidth + tileHeight + jointWidth) * tileThickness * jointWidth * (144 / ((tileWidth + jointWidth) * (tileHeight + jointWidth))));
if (_previousModel.SelectedUnit.Code == UnitCode.Metric)
{
// Convert coverages to metric units if necessary (sqft to m2)
adhesiveCoverage *= 0.092903;
groutCoverage *= 0.092903;
}
TileSize = $"{_previousModel.TileWidth}{lengthUnits} x {_previousModel.TileHeight}{lengthUnits}";
TileThickness = _previousModel.SelectedTileThickness.Value;
JointSize = _previousModel.SelectedJointSize.Value;
TrowelSize = _previousModel.SelectedTrowelSize.Value;
Adhesive = _previousModel.SelectedAdhesive.Name;
AdhesiveCoverage = $"Adhesive Coverage per Unit*: {adhesiveCoverage: #.##}{coverageUnits}";
Grout = _previousModel.SelectedGrout.Name;
GroutCoverage = $"Grout Coverage per Unit*: {groutCoverage: #.##}{coverageUnits}";
}
catch(Exception ex)
{
HandleException(ex, true);
}
}
All the data is obtained from the user on the previous page or from the calculations shown above.

adding listview hides form background image Xamarin ios

I am working on Xamarin cross platform app.
I have have form where I am using form's BackgroundImage = "timelinebackground.png"; on constructor to set background image.
Its working on fine Android but when I check same in iOS it's not showing background image.
When I remove listview from xaml then its background image is showing in iOS as well.
here is xaml
<?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="BMTHomesApp.Views.Timeline">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Logout" Order="Primary" Priority="0" Clicked="MenuItem_OnClicked"></ToolbarItem>
</ContentPage.ToolbarItems>
<StackLayout>
<ListView
x:Name="timelineListView"
ItemTapped="timelineListView_ItemTapped"
ItemsSource="{Binding .}"
RowHeight="75"
SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid ColumnSpacing="0" RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="25" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label HorizontalOptions="Center" Text="{Binding ActualStartDate}" TextColor="#0073ae" />
<Label Grid.Column="2" Margin="20,0" FontSize="Medium" Text="{Binding StageName}" TextColor="#ffffff"/>
<!--<Label
Grid.Row="1"
Grid.Column="2"
Margin="20,0"
FontSize="Small"
Text="Please add some desc text in api" TextColor="#ffffff"/>-->
<BoxView
Grid.RowSpan="2"
Grid.Column="1"
BackgroundColor="#ffffff"
HorizontalOptions="Center"
VerticalOptions="Fill"
WidthRequest="1" />
<Image Grid.Column="1" Source="Bullet.png" HeightRequest="25" WidthRequest="25" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<DatePicker x:Name="DatePickerTimeline" IsVisible="False"></DatePicker>
</StackLayout>
</ContentPage>
and code behind:
public partial class Timeline : ContentPage
{
public Timeline ()
{
InitializeComponent ();
NavigationPage.SetBackButtonTitle(this, "");
Title = "TIMELINE";
BackgroundImage = "timelinebackground.png";
var constructionStages = GetConstructionStages();
if (!string.IsNullOrEmpty(constructionStages.Result.Error))
{
DisplayAlert("Error", constructionStages.Result.Error, "Ok");
}
else
{
timelineListView.ItemsSource = constructionStages.Result.ConstructionStages;
}
}
private void timelineListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var selectedItem = (ConstructionStages) e.Item;
if (!string.IsNullOrEmpty(selectedItem.ActualStartDate))
{
DateTime dateTimeStart;
if (DateTime.TryParse(selectedItem.ActualStartDate, out dateTimeStart))
{
DatePickerTimeline.MinimumDate = dateTimeStart;
}
}
if (!string.IsNullOrEmpty(selectedItem.ActualCompletionDate))
{
DateTime dateTimeEnd;
if (DateTime.TryParse(selectedItem.ActualCompletionDate, out dateTimeEnd))
{
DatePickerTimeline.MaximumDate = dateTimeEnd;
}
}
if (!string.IsNullOrEmpty(selectedItem.ActualStartDate) ||
!string.IsNullOrEmpty(selectedItem.ActualCompletionDate))
{
DatePickerTimeline.Format = "MM-dd-yyyy";
DatePickerTimeline.BackgroundColor = Color.FromHex("#ffffff");
//DatePickerTimeline.IsVisible = true;
DatePickerTimeline.Focus();
}
else
{
timelineListView.SelectedItem = null;
}
}
private async Task<ConstructionStagesResponse> GetConstructionStages()
{
ConstructionStageManager manager = new ConstructionStageManager();
var result = await manager.GetConstructionStages(Application.Current.Properties["SessionId"].ToString());
return result;
}
private async void MenuItem_OnClicked(object sender, EventArgs e)
{
HelperClasses.LogOut();
Application.Current.MainPage = new NavigationPage(new Login());
//Navigation.PushAsync(new Login());
}
}
You need to set your ListView's BackgroundColor property to transparent for the Page's background image to be shown:
<ListView BackgroundColor="Transparent">

Listview not updated when isVisible is set to true

I'm trying to make a ListView with clickable rows. When you click on a row it sets a child stacklayout to visibility true. This works fine in android, but not in ios. Maybe I'm doing it the wrong way. I am still a beginner, any idea how to fix this or any other better approach?
The problem is that it opens on ios so the visibility changes, but it does not update the height of the cell. The cell updates off-screen for example if you scroll up until you can't see the opened cell anymore and then scroll back down. You'll see it has updated the height.
I tried using a custom renderer, but i have no idea where to start.
This is my xaml:
<?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="Lisa.Excelsis.Mobile.AssessmentPage" xmlns:local="clr-namespace:Lisa.Excelsis.Mobile;assembly=Lisa.Excelsis.Mobile">
<StackLayout>
<local:SpecialListView x:Name="CategoryList"
ItemsSource = "{Binding Categories}"
HasUnevenRows="true"
RowHeight="-1"
GroupDisplayBinding="{Binding Name}"
IsGroupingEnabled="true">
<local:SpecialListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="ObservationCell">
<ViewCell.View>
<StackLayout x:Name="ObservationContainer"
HorizontalOptions="FillAndExpand"
Orientation="Vertical"
VerticalOptions="StartAndExpand"
BackgroundColor="White">
<StackLayout x:Name="Observation"
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand"
Padding="15, 10, 10, 10"
BackgroundColor="White">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="OpenItem"/>
</StackLayout.GestureRecognizers>
<Grid HorizontalOptions="FillAndExpand" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="35" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="ObservationOrder"
Text="{Binding Criterion.Order, StringFormat='{0}.'}"
FontSize="18"
VerticalOptions="StartAndExpand"
Grid.Column="0" Grid.Row="0"/>
<Label x:Name="ObservationTitle"
Text="{Binding Criterion.Title}"
FontSize="18"
VerticalOptions="StartAndExpand"
Grid.Column="1" Grid.Row="0"/>
</Grid>
</StackLayout>
<StackLayout x:Name="ObservationButtons"
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand"
BackgroundColor="White"
IsVisible="false"
Padding="0, 0, 0, 20"
ClassId = "{Binding Id, StringFormat='ObservationButtons_{0}'}">
<Grid HorizontalOptions="Center"
Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0" Grid.Row="0" >
<Image Source="yesnobutton0.png"
HeightRequest="60" WidthRequest="60"
HorizontalOptions="Center"
VerticalOptions="Start"
x:Name="yesImage">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="SetYesImage"/>
</Image.GestureRecognizers>
</Image>
<Label Text="Ja" VerticalOptions="End" HorizontalOptions="Center"/>
</StackLayout>
<StackLayout Grid.Column="1" Grid.Row="0">
<Image Source="yesnobutton0.png"
HeightRequest="60" WidthRequest="60"
HorizontalOptions="Center"
VerticalOptions="Start"
x:Name="noImage">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="SetNoImage"/>
</Image.GestureRecognizers>
</Image>
<Label Text="Nee" VerticalOptions="End" HorizontalOptions="Center"/>
</StackLayout>
<Image Source="maybenot.png"
HeightRequest="60" WidthRequest="60"
HorizontalOptions="Center"
VerticalOptions="Start"
Grid.Column="3" Grid.Row="0">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="SetMark"/>
</Image.GestureRecognizers>
</Image>
<Image Source="skip.png"
HeightRequest="60" WidthRequest="60"
HorizontalOptions="Center"
VerticalOptions="Start"
Grid.Column="4" Grid.Row="0">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="SetMark"/>
</Image.GestureRecognizers>
</Image>
<Image Source="unclear.png"
HeightRequest="60" WidthRequest="60"
HorizontalOptions="Center"
VerticalOptions="Start"
Grid.Column="5" Grid.Row="0">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="SetMark"/>
</Image.GestureRecognizers>
</Image>
<Image Source="change.png"
HeightRequest="60" WidthRequest="60"
HorizontalOptions="Center"
VerticalOptions="Start"
Grid.Column="6" Grid.Row="0">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="SetMark"/>
</Image.GestureRecognizers>
</Image>
</Grid>
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</local:SpecialListView.ItemTemplate>
</local:SpecialListView>
</StackLayout>
This is an example of how it works on android and how i want it to work on ios.
I reproduced your Problem in a small Testproject. I prefer doing layout changes via data binding, instead of code behind.
Let's start with the Template:
<?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="App6.Page1">
<ListView x:Name="CategoryList"
BackgroundColor="Gray"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedItem}"
HasUnevenRows="true"
RowHeight="-1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="ObservationCell">
<ViewCell.View>
<StackLayout x:Name="Observation"
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand"
Padding="15, 10, 10, 10"
BackgroundColor="White">
<Label x:Name="ObservationTitle"
Text="{Binding Title}"
FontSize="18"
TextColor="Black"
VerticalOptions="StartAndExpand"/>
<StackLayout Orientation="Horizontal" IsVisible="{Binding IsSelected}">
<Image BackgroundColor="Fuchsia" WidthRequest="40" HeightRequest="40"></Image>
<Image BackgroundColor="Green" WidthRequest="40" HeightRequest="40"></Image>
<Image BackgroundColor="Yellow" WidthRequest="40" HeightRequest="40"></Image>
<Image BackgroundColor="Blue" WidthRequest="40" HeightRequest="40"></Image>
<Image BackgroundColor="Black" WidthRequest="40" HeightRequest="40"></Image>
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
The Datatemplate is basicaly the same, but:
the StackLayout has no Click-Listener
the Visbility of the StackLayout is bound to IsSelected (IsVisible="{Binding IsSelected}")
the SelectedItem of the ListView is bound to SelectedItem of our ViewModel
Our Page just sets the ViewModel as DataContext
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
BindingContext = new Page1ViewModel();
}
}
The ViewModel
implements INotifyPropertyChanged to notify the view about data changes
adds some dummy items to our Categories Collection
has a SelectedItem property that updates the IsSelected property of the Categories
class Page1ViewModel : INotifyPropertyChanged
{
private Category _selectedItem;
private ObservableCollection<Category> _categories = new ObservableCollection<Category>();
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Category> Categories
{
get { return _categories; }
set
{
_categories = value;
OnPropertyChanged();
}
}
public Category SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem == value)
return;
if (_selectedItem != null)
{
_selectedItem.IsSelected = false;
}
_selectedItem = value;
if (_selectedItem != null)
{
_selectedItem.IsSelected = true;
}
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public Page1ViewModel()
{
Categories.Add(new Category());
Categories.Add(new Category());
Categories.Add(new Category());
Categories.Add(new Category());
Categories.Add(new Category());
}
}
Last, but not least, but most important, you need a tiny custom renderer that overwrites the default one. We call ReloadData() if the SelectedItem has changed.
[assembly: ExportRenderer(typeof(ListView), typeof(MyListViewRenderer))]
namespace App6.iOS.CustomRenderer
{
public class MyListViewRenderer : ListViewRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == ListView.SelectedItemProperty.PropertyName)
{
Device.BeginInvokeOnMainThread(() => Control.ReloadData());
}
}
}
}
Result

Binding fails when moved into a flyout

I have a slider bound to the volume property of a MediaElement. This works if marked up as below:
<UserControl
x:Class="GenTest.VideoElement"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:GenTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="600">
<UserControl.Resources>
<Style x:Name="transportStyle" TargetType="Button">
<Setter Property="Height" Value="40" />
<Setter Property="Width" Value="75" />
<Setter Property="FontSize" Value="11" />
</Style>
<Style x:Name="atransportStyle" TargetType="AppBarButton">
<Setter Property="IsCompact" Value="true" />
<Setter Property="FontSize" Value="11" />
</Style>
</UserControl.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<ContentControl x:Name="videoContainer"
KeyUp="VideoContainer_KeyUp"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Height="400" Grid.Row="0" >
<MediaElement Name="videoMediaElement"
MediaOpened="videoElement_MediaOpened"
MediaEnded="videoMediaElement_MediaEnded"
MediaFailed="videoMediaElement_MediaFailed"
CurrentStateChanged="videoMediaElement_CurrentStateChanged"
AutoPlay="False" />
</ContentControl>
<!-- Transport Controls -->
<StackPanel Name="TransportControlsPanel"
HorizontalAlignment="Center"
Grid.Row="1" >
<Slider Name="timelineSlider" Margin="0,0" Width="500" Height="37"/>
<StackPanel Orientation="Horizontal">
<AppBarButton x:Name="btnPlay" Icon="Play" Click="btnPlay_Click" Style="{StaticResource atransportStyle}" Label="Play"/>
<AppBarButton x:Name="btnStop" Icon="Stop" Click="btnStop_Click" Style="{StaticResource atransportStyle}"/>
<AppBarButton x:Name="btnReverse" Icon="Previous" Click="btnReverse_Click" Style="{StaticResource atransportStyle}"/>
<AppBarButton x:Name="btnForward" Icon="Next" Click="btnForward_Click" Style="{StaticResource atransportStyle}"/>
<Button Name="btnFullScreenToggle" Click="btnFullScreenToggle_Click"
Style="{StaticResource transportStyle}" Content="Full" />
<ComboBox Name="cbAudioTracks"
SelectionChanged="cbAudioTracks_SelectionChanged"
Width="75" />
<AppBarButton x:Name="btnTest" Icon="Other" Style="{StaticResource atransportStyle}">
<AppBarButton.Flyout>
<Flyout>
<StackPanel Orientation="Vertical">
</StackPanel>
</Flyout>
</AppBarButton.Flyout>
</AppBarButton>
<Slider Minimum="0" Maximum="1" StepFrequency="0.1" Height="100" Value="{Binding Mode=TwoWay,
ElementName=videoMediaElement, Path=Volume}" Orientation="Vertical"/>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
But when I put the slider into the Flyout the Binding no longer works.
<AppBarButton x:Name="btnTest" Icon="Other" Style="{StaticResource atransportStyle}">
<AppBarButton.Flyout>
<Flyout>
<StackPanel Orientation="Vertical">
<Slider Minimum="0" Maximum="1" StepFrequency="0.1" Height="100" Value="{Binding Mode=TwoWay,
ElementName=videoMediaElement, Path=Volume}" Orientation="Vertical"/>
</StackPanel>
</Flyout>
</AppBarButton.Flyout>
</AppBarButton>
There are no errors and I cant do a Binding trace because the TraceListeners have been removed from WinRt. I have tried:
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.UnhandledException += App_UnhandledException;
DebugSettings.BindingFailed += OnDebugSettingsOnBindingFailed;
}
private void OnDebugSettingsOnBindingFailed(object sender, BindingFailedEventArgs args)
{
new MessageDialog(args.Message).ShowAsync();
}
But no errors are thrown and there is nothing in the output window. In design mode, using the Properties Windows, if i change the volume value of the videoMediaElement then the Value property of the Slider changes but I cant update the Value of the slider, it's read only.
I can make it work within the flyout if I use code:
private void RangeBase_OnValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
var slider = sender as Slider;
videoMediaElement.Volume = slider.Value;
}
but then why bother with bindings at all?
I had this kind of errors some times now, I think that Flyouts are handled separately where the Bindings can't look for the ElementName.
I suggest that you should do this with a ViewModel, instead of cross binding in your Page
Slider.Value [TwoWay-Bind] -> ViewModel.Volume
ViewModel.Volume -> videoMediaElement.Volume

How to add different background colors to alternate rows to list box items windows phone 8

I'm new to windows phone development.
I'm showing data in list box. For for all rows in the list box the back ground color is same.
But I want to add two different colors for alternate rows to list box items.
Below is the code for list view.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,10,0,0" Background="White">
<ListBox Margin="6,6,-6,6" Name="itemslb" SelectionChanged="itemList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="listItem">
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="10"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Height="100" Margin="0,10,0,0">
<StackPanel Width="85" Height="100" >
<StackPanel.Background>
<ImageBrush x:Name="defImage" ImageSource="/DailyFeeds;component/Images/default.png" Stretch="None"></ImageBrush>
</StackPanel.Background>
<Image Source="{Binding ImageUrl}" VerticalAlignment="Top" Height="90" Width="85" Margin="0,0,10,0" Stretch="Fill" />
</StackPanel>
<StackPanel Width="370">
<TextBlock Text="{Binding Title}" Foreground="SlateBlue" FontSize="25" TextWrapping="Wrap" />
<TextBlock Text="{Binding Date}" Foreground="#FFC8AB14" FontSize="20"/>
</StackPanel>
</StackPanel>
<Image x:Name="line" Grid.Row="1" Width="460" HorizontalAlignment="Center" Margin="0,5,0,0" Source="/DailyFeeds;component/Images/separator.png" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
How can we do that.
Thanks
create a converter class
public class AlternateRowColour : IValueConverter
{
bool isAlternate;
SolidColorBrush even = new SolidColorBrush(Colors.Transparent); // Set these two brushes to your alternating background colours.
SolidColorBrush odd = new SolidColorBrush(Color.FromArgb(255, 241, 241, 241));
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
isAlternate = !isAlternate;
return isAlternate ? even : odd ;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
add converter to the page
<UserControl
xmlns:conv="clr-namespace:MyApplication.Converters"
<UserControl.Resources>
<conv:AlternateRowColour x:Key="RowColour" />
</UserControl.Resources>
</UserControl>
ur listBox
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Background="{Binding Converter={StaticResource RowColour}}"> // your stackPanel
<!-- layout XAML -->
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Define a Class
public class RowData
{
public string text { get; set; }
public Brush brush { get; set; }
}
XAML Code
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="60" Width="480" Background="{Binding brush}">
<TextBlock VerticalAlignment="Center" Margin="12,0" Text="{Binding text}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
C# code
ObservableCollection<RowData> items = new ObservableCollection<RowData>();
items.Add(new RowData() { text = "Text 1", brush = new SolidColorBrush(Colors.Red) });
items.Add(new RowData() { text = "Text 2", brush = new SolidColorBrush(Colors.Green) });
items.Add(new RowData() { text = "Text 3", brush = new SolidColorBrush(Colors.Red) });
items.Add(new RowData() { text = "Text 4", brush = new SolidColorBrush(Colors.Green) });
items.Add(new RowData() { text = "Text 5", brush = new SolidColorBrush(Colors.Red) });
listBox.ItemsSource = items;
or:
<Grid>
<Grid.Resources>
<AlternationConverter x:Key="BackgroundConverter">
<SolidColorBrush>Blue</SolidColorBrush>
<SolidColorBrush>CornflowerBlue</SolidColorBrush>
<SolidColorBrush>LightBlue</SolidColorBrush>
</AlternationConverter>
<AlternationConverter x:Key="AlternateForegroundConverter">
<SolidColorBrush>White</SolidColorBrush>
<SolidColorBrush>Black</SolidColorBrush>
<SolidColorBrush>Navy</SolidColorBrush>
</AlternationConverter>
<Style x:Key="alternatingWithBinding" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(ItemsControl.AlternationIndex),
Converter={StaticResource BackgroundConverter}}"/>
<Setter Property="Foreground"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(ItemsControl.AlternationIndex),
Converter={StaticResource AlternateForegroundConverter}}"/>
</Style>
</Grid.Resources>
<ListBox AlternationCount="3" ItemsSource="{StaticResource data}"
ItemContainerStyle="{StaticResource alternatingWithBinding}"/>
</Grid>

Resources