Binding a list to a Gridview - c#

I'm struggling to get my head around this, i have a list collection with the following that i'm trying to bind to a GridView;
public class GetMenu
{
public string titleName { get; set; }
public string imagePath { get; set; }
}
List<GetMenu> Menu = new List<GetMenu>()
{
new GetMenu(){titleName = "one", imagePath = "image.jpg"},
new GetMenu(){titleName = "one", imagePath = "image.jpg"}
};
My XAML code looks like;
<GridView x:Name="MenuViewGrid" TabIndex="1"
Grid.RowSpan="2" Padding="116,136,116,46" Margin="0,0,50,0" VerticalAlignment="Center"
SelectionMode="None" IsSwipeEnabled="false" IsItemClickEnabled="True" ItemClick="ItemView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Width="275" Height="425" >
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding Path=imagePath}" Stretch="UniformToFill"/>
</Border>
<StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding Path=titleName}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" FontSize="25" Height="60" Margin="15,0,15,0"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
In my head i thought i'd be able to do a simple;
MenuViewGrid.ItemsSource = GetMenu;
But when doing the above i get an error message saying it's a type but i'm trying to use it as a variable. I can't understand this as i've used the code on Windows Phone before.

Replace GetMenu by Menu (GetMenu is your class, Menu is your list):
MenuViewGrid.ItemsSource = Menu;

Related

Databinding to command inside of listview not working in UWP/MVVM-Light

I want to have a Delete button for every element in my ListView, I searched stackoverflow but none answer my question.
I tried giving my ListView a x:Name="QuizListView" and using ElementName inside the ListView to bind the command to the button.
QuizOverview.xaml
<Page
x:Name="QuizOverviewPage"
x:Class="UwpApp.View.QuizOverview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UwpApp.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding QuizOverviewInstance, Source={StaticResource Locator}}">
<StackPanel Margin="20">
<TextBlock Text="Quizzen" FontSize="48"/>
<ListView x:Name="QuizListView" ItemsSource="{Binding Quizzes}" Margin="0,20" SelectionMode="Single" SelectionChanged="QuizListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<ListViewItem>
<StackPanel Orientation="Horizontal">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="2" Height="100" Width="400" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="36"></TextBlock>
</Border>
<Button VerticalAlignment="Center" Padding="20" Margin="20">Edit</Button>
<Button VerticalAlignment="Center" Padding="20" Margin="0" Command="{Binding Path=DataContext.DeleteQuizCommand, ElementName=QuizListView}" CommandParameter="{Binding}">Delete</Button>
</StackPanel>
</ListViewItem>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Padding="20" Command="{Binding CreateQuizCommand}">Add New Quiz</Button>
</StackPanel>
</Page>
QuizOverviewViewModel.cs
public class QuizOverviewViewModel : ViewModelBase
{
public string Title { get; set; }
public ObservableCollection<Quiz> Quizzes { get; set; }
public RelayCommand<Quiz> DeleteQuizCommand { get; set; }
public RelayCommand CreateQuizCommand { get; set; }
public QuizOverviewViewModel()
{
Title = "Quizzen";
Quizzes = new ObservableCollection<Quiz> { new Quiz(1, "Test Quiz 1"), new Quiz(2, "Test Quiz 2"), new Quiz(3, "Test Quiz 3") };
DeleteQuizCommand = new RelayCommand<Quiz>(DeleteQuiz);
CreateQuizCommand = new RelayCommand(CreateQuizTest);
}
public void DeleteQuiz(Quiz quiz)
{
Quizzes.Remove(Quizzes.Single(i => i.Id == quiz.Id));
}
public void CreateQuizTest()
{
Quizzes.Add(new Quiz(4, "Test Quiz Creation!"));
}
}
Quiz.cs
namespace UwpApp.Model
{
public class Quiz
{
public long Id { get; set; }
public string Name { get; set; }
public Quiz(long id, string name)
{
Id = id;
Name = name;
}
}
}
The Button does nothing with my current code, while the command does work outside of the ListView.
Databinding to command inside of listview not working in UWP/MVVM-Light
The problem is that you insert ListViewItem in to DataTemplate. It will cause that ListViewItem contains sub-ListViewItem in the Visual Tree and you could not access correct DataContext with element name in your button. Please remove ListViewItem from your code.
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="2" Height="100" Width="400" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="36"></TextBlock>
</Border>
<Button VerticalAlignment="Center" Padding="20" Margin="20">Edit</Button>
<Button VerticalAlignment="Center" Padding="20" Margin="0" Command="{Binding Path=DataContext.DeleteQuizCommand, ElementName=QuizListView}" CommandParameter="{Binding}">Delete</Button>
</StackPanel>
</DataTemplate>

windows phone 8.1: Hide stackpanel if textblock is empty

my xaml code is given below
my whole xaml
<Page
x:Class="App13.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App13"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:converter="using:App13"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<converter:BooleanToVisibilityConvertor x:Key="visibilityConverter"/>
</Page.Resources>
<Grid Margin="0,30.333,0,-0.333" Background="Black" >
<!--<Button Margin="0,-105,0,563" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollMode="Enabled" x:Name="one" Content="Getdata" RenderTransformOrigin="0.367,-0.585" Height="92" Width="112" Click="Button_Click"/>-->
<ListView IsItemClickEnabled="True" IsEnabled="True" ItemClick="listview1_ItemClick" ScrollViewer.VerticalScrollMode="Enabled" ScrollViewer.VerticalScrollBarVisibility="Visible" x:Name="listview1" ItemsSource="{Binding Taxi}" FontSize="17" Margin="10,0,-10,0">
<ListView.Items>
<StackPanel Background="Blue">
<TextBlock Text="eqweqwe" Foreground="AntiqueWhite"></TextBlock>
<TextBlock Foreground="Aqua" Text="sadwdasdasdasd"></TextBlock>
</StackPanel>
</ListView.Items>
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Border Tapped="Border_Tap" Height="90">
<StackPanel x:Name="ParentStackPanel" Width="380" Margin="0,5,0,5">
<StackPanel Margin="0,-80,0,0" Background="Black" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Left">
<Image Width="48"
Height="48"
Source="{Binding Icon}"
/>
</StackPanel>
<StackPanel Name="expand" Background="White" Height="220" >
<StackPanel Orientation="Horizontal" Margin="10,10,0,0" Visibility="{Binding Invoice.Minimum_Fare, Converter={StaticResource visibilityConverter}}">
<TextBlock AllowDrop="True" Grid.Column="1" Margin="50,0,0,0" HorizontalAlignment="Left" FontSize="10" Foreground="Black" Text="Approx Travel Time" ></TextBlock>
<TextBlock Name="tb" Grid.Column="2" HorizontalAlignment="Right" AllowDrop="True" FontSize="6" Foreground="Black" Width="204" Text="{Binding Invoice.Minimum_Fare}" >
</TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10,3,0,0" >
<TextBlock Width="183" Margin="50,0,0,0" FontSize="16" Foreground="Black" Text="Minimum Fare"></TextBlock>
<TextBlock FontSize="16" Foreground="Black" Text="{Binding Invoice.Minimum_Fare}" Width="131">
</TextBlock>
</StackPanel>
<StackPanel Margin="0,5,0,5" Height="5" Grid.Row="1" Background="Aqua" x:Name="something">
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
using visualstatemanager or some front end techniques i want to hide stackpanel if the textblock text is empty
I modal is this
public class Example {
public string CompanyName { get; set;}
public string Invoice { get; set; }
public string Lat { get; set; }
public string Lng { get; set; }
}
by i dont know how to bind visibility with stack panel
You can write converter to hide/show stackpanel
public class BooleanToVisibilityConvertor: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if(value!=null)
{
if (!string.IsNullOrEmpty(value.ToString()))
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
In xaml add converter
<Page
x:Class="App1.MainPage"
xmlns:converter="using:App1">
<Page.Resources>
<converter:BooleanToVisibilityConvertor x:Key="visibilityConverter"/>
</Page.Resources>
<StackPanel Background="Aqua" Height="200" Orientation="Horizontal" Margin="10,3,0,0" Visibility="{Binding Invoice, Converter={StaticResource visibilityConverter}}">
<TextBlock FontSize="16" Text="{Binding Invoice}" Name="tb" Height="300" Width="300" Foreground="Black" >
</TextBlock>
</StackPanel>
I have hardcoded text value for testing. You can use binding.
Check and let me know if any issue.
You cannot do this with visual states in Windows Phone 8. I suggest you create a simple StringToVisibilityConverter (returning Visibility.Collapsed on empty string) and use it to bind your StackPanel visibility.
<StackPanel Visibility="{Binding Path=stcVisiblity}" >
<TextBlock FontSize="16" Foreground="Black" Text="{Binding Invoice}">
</TextBlock>
</StackPanel>
and the class
public class Example {
public string CompanyName { get; set;}
public string Invoice { get; set; }
public string Lat { get; set; }
public string stcVisiblity { get; set; }
public string Lng { get; set; }
}
and than code
something like this to code,
than you can bind this value as per your need :
stcVisiblity = "Visible"; or
stcVisiblity = "Collapsed";

Win 8 App Set text in data template

Im trying to learn how to make datatemplate in listviews in my win 8 app
I have the following code in my Xaml code
<!-- Vertical scrolling item list -->
<ListView x:Name="itemListView"
Margin="120,0,0,60"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
SelectionChanged="ItemListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="110" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
<Image Source="{Binding Image}" Stretch="UniformToFill"/>
</Border>
<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Text="{Binding Title}" TextWrapping="NoWrap" FontFamily="Global User Interface"/>
<TextBlock Text="{Binding Subtitle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Description}" MaxHeight="60" FontFamily="Global User Interface"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
What I cant work out is how to set the text for the three text blocks Title,Subtitle & Description as well as the Picture in Image
Usually When the page loads I use the following in my itemListView_Loaded(object sender, RoutedEventArgs e) method
itemListView.Items.Add(Convert.ToString(correct) + ". " + line.Split(',')[6]);
But how do I do it Im really stumped
Any help appreciated
Mark
You'll have to make a class which includes those properties.
public class MyItem
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public string Source { get; set; }
}
Then when you add items:
var item = new MyItem();
item.Title = "Title";
item.Subtitle = "Subtitle";
item.Description = "Some example description.";
item.Source = "Assets/SomeFolder/SomeImage.png";
itemListView.Items.Add(item);
That worked in my app (AirPett Transit)

Values from database not showing up on xaml page after using groupby statement

I have a dto,method and xaml file below. The method returns duplicates which is fine. I only want to display one on my xaml page. I used a groupby and I was able
to display one item but the values for RouteNbr and Day are not displayed on the xaml page.
Do you know what am doing wrong?
public class CSDto
{
public Int32 ID { get; set; }
public Int32 RouteNbr { get; set; }
public Int32 Day { get; set; }
public String Month { get; set; }
public String Year { get; set; }
}
private void GetAllCsrActPlansByCsrId(Int32 CssId)
{
try
{
string getCs = Convert.ToString(CssId);
var getRouteInfoProfile = MySol.GetByCustomerNbr(getCs);
var queryResult = getRouteInfoProfile;
grdVwRouteAct.DataContext = queryResult.GroupBy(g=>g.RouteNbr).Distinct();
}
catch (Exception ex)
{
customutility.ApplicationErrorlog(UserID, ex.Message, DateTime.Now.ToString());
}
}
<GridView.ItemTemplate>
<DataTemplate>
<Button Style="{StaticResource CSRProfile}" Margin="0" Padding="0" Height="Auto" Width="Auto" Background="MediumAquamarine">
<StackPanel Tag="cpActionPlanBlock" Width="275" Height="90" HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Margin="0">
<Image Source="/Assets/Images/CSRProfile-checkicon.gif" Width="49" Height="65" VerticalAlignment="Center" Margin="10"/>
<StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="10,0">
<StackPanel Orientation="Horizontal">
<TextBlock Tag="cpRouteNumber" Style="{ThemeResource BasicFontStyle4B}" Text="{Binding RouteNbr}" VerticalAlignment="Top" Margin="0,0,0,5"/>
<TextBlock Style="{ThemeResource BasicFontStyle4B}" Text="-" VerticalAlignment="Top" Margin="5,0,5,0"/>
<TextBlock Tag="cpDay" x:Uid="queueItemType" Style="{ThemeResource BasicFontStyle4B}" Text="{Binding Day}" VerticalAlignment="Top" Margin="0,0,0,5"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Tag="cpNumberofActions" Style="{ThemeResource BasicFontStyle4B}" Text="[Y]" VerticalAlignment="Top" Margin="0,0,5,0"/>
<TextBlock Tag="cpLblActions" Style="{ThemeResource BasicFontStyle4B}" Text="Actions" x:Uid="cpActions" VerticalAlignment="Top" Margin="0,0,15,5"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Button>
</DataTemplate>
</GridView.ItemTemplate>

Display multiple local database value in listbox

I'm trying to list out data from a local database to a list box for WP8.1
.xaml:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source= "**Fruit Image**" Height="26" Width="50" Margin="12,10,9,0" VerticalAlignment="Top"/>
<TextBlock Text="**Fruit Name**" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
<TextBlock Text="**Fruit Colour**" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Getting value from my database
.cs:
public void ListFruit()
{
using (var db = new SQLite.SQLiteConnection(this.DBPath))
{
List<Fruits> retrievedTasks = db.Table<Fruits>().ToList<Fruits>();
}
}
.cs
public class Fruits
{
public string ImgPath { get; set; }
public string FruitName { get; set; }
public string FruitColour{ get; set; }
}
I'm not really sure if the method i'm using is correct, please guide me. Thanks!
You have defined properties in your class, you have filled your List<Fruit> with items.
What you should else do is (if you haven't done it already):
Define your List<Fruit> as ItemsSource of Listbox
public void ListFruit()
{
using (var db = new SQLite.SQLiteConnection(this.DBPath))
{
List<Fruits> retrievedTasks = db.Table<Fruits>().ToList<Fruits>();
myListbox.ItemsSource = retrievedTasks; // or directly
}
}
You may also think of using ObservableCollection instead of List - in this case you need to set ItemsSource only once - for example in constructor of the Page. You may also think of implementing INotifyPropertyChanged so that you can inform View when item changes.
And I'm not sure if you had defined Binding in your xaml (or somewhere else):
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source= "{Binding ImgPath}" Height="26" Width="50" Margin="12,10,9,0" VerticalAlignment="Top"/>
<TextBlock Text="{Binding FruitName}" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
<TextBlock Text="{Binding FruitColour}" FontSize="26" Style="{StaticResource BodyTextBlockStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>

Categories