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

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>

Related

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">

UWPCommunityToolkit's PrintHelper produce blank output

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

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

listbox not showing all items windows phone 8.1

I'm trying to populate a listbox using binding in windows phone 8.1. I can't see all of the items in the control.
XAML:
<Grid x:Name="LayoutRoot">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Title Panel -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Text="Application Name" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel>
<StackPanel Grid.Row="1" x:Name="ContentRoot" Margin="19,0,19,0">
<ComboBox
x:Name="ComboBox1"
ItemsSource="{Binding}"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
SelectionChanged="ComboBox1_SelectionChanged"
/>
<ListBox x:Name="ListBox1" ItemsSource="{Binding}" Height="1000">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Margin="0">
<TextBlock Text="{Binding GameName}" Margin="2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
I populate the listbox in code:
private ObservableCollection<Game> _Games = new ObservableCollection<Game>();
public StartPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
ListBox1.DataContext = _Games;
}
....
private async void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var group = _Groups[ComboBox1.SelectedIndex];
games = await DataServer.GetGamesAsync(group.GroupName);
_Games.Clear();
foreach (var game in games.OrderBy(g => g.GameName))
{
_Games.Add(game);
}
}
There are 69 games but I can only see about 28 in the list view in the emulator when I scroll the list. It's clear that there are more items in the list, but I can't scroll to them. Any help is appreciated.
Replace the StackPanel with a Grid and add a couple more RowDefinitions in the second Grid you'll add. StackPanels don't size themselves dynamically, so instead of sizing to the screen, it's just stretched infinitely to the bottom.

Textblock text not wrapping in wp7 app

new to wp7 and i have not the faintest idea why the textblock text is not wrapping?
<Popup x:Name="EulaPopUp" IsOpen="False">
<Grid Background="White" Width="{Binding ElementName=LayoutRoot, Path=Width}" Height="{Binding ElementName=LayoutRoot, Path=Height}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<TextBlock Foreground="Black" Text="End User License Agreement" VerticalAlignment="Top" Grid.Row="0"/>
<ScrollViewer HorizontalAlignment="Left" Name="scrollViewer1" Width="{Binding ElementName=ContentPanel, Path=Width}" VerticalAlignment="Top" Margin="0,30,0,0" Grid.Row="1">
<TextBlock Name="eulaTxt" Width="{Binding ElementName=ContentPanel, Path=Width}" Text="{Binding Path=AppResources.EULA, Source={StaticResource AppResources} }" HorizontalAlignment="Left" VerticalAlignment="Top" TextWrapping="Wrap" />
</ScrollViewer>
<Button Grid.Row="2" Content="I Agree" Background="Green" Height="70" HorizontalAlignment="Center" Margin="0" Name="EulaOK" VerticalAlignment="Bottom" Width="160" />
</Grid>
</Popup>
I'm binding the widths of the elements so that when the device reorients the widths adjust accordingly. Is this wrong? How can I fix it? Thanks
U can actually customize ur message box..something like this ...
public static void customizedMessageBox(int messageboxtype, string title, string text, IEnumerable<string> buttons, int focusbutton, MessageBoxIcon icon, AsyncCallback callback, object state)
{
if (!Guide.IsVisible)
{
try
{
ProgressBarControl.dismissProgressBar();
Guide.BeginShowMessageBox(" ", text, buttons, focusbutton, MessageBoxIcon.None, callback, state);
messageboxType = messageboxtype;
}
catch (GuideAlreadyVisibleException ex)
{
Logger.log("MsgBox", "Exception : messageboxtype: " + messageboxtype
+ "\n" + ex.Message + "\n" + ex.StackTrace);
}
}
//return messageboxtype;
}
and for ur text wrapping query.. I have the same type of design in my app..i.e, Eula screen to present the license agreement .. what we have used is something like this..
<Grid x:Name="EulaGrid" Grid.Row="1" Visibility="Collapsed">
<ListBox x:Name="lbEula" Margin="18,100,19,135" ScrollViewer.VerticalScrollBarVisibility="Visible" Style="{StaticResource ListBoxStyle1}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap"
IsHitTestVisible="False"
Width="Auto" FontFamily="Arial" FontSize="18" Foreground="Black" x:Name="eulaText" Grid.ColumnSpan="2" Grid.Column="2"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
make the width Auto so that it will adjust accordingly for both orientations.. I hope it helps u.. Gud luck :)
I'm curious as to why you're not using a MessageBox to show the License Agreement in, rather than attempting to re-create it as a custom control?

Resources