windows phone 7, can't bind an image to stackpanel properly - xaml

Binded image refuses to be displayed. Could anyone give some hints?
This is XAML:
<ListBox Name="TransactionList" Margin="0,0,0,78">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Width="460" Height="100">
<Button.Content>
<StackPanel Orientation="Horizontal" Height="80" Width="400">
<Image Source="{Binding Pic}" Margin="2" Width="80" Height="80" Stretch="Fill" Style="{Binding}" />
<StackPanel Orientation="Vertical" Height="40">
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="100" FontSize="22" Text="{Binding Name}" Height="40" Style="{Binding}" />
<TextBlock Width="200" FontSize="22" Text="{Binding Surname}" Height="40"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="200" FontSize="22" Text="{Binding Number}" Height="40" Style="{Binding}" />
</StackPanel>
</StackPanel>
</StackPanel>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is how it should look like
And this what I got
Image and Number are not displayed...
Here's the MainPage structure:
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
List<Transaction> transactionList = new List<Transaction>();
transactionList.Add(new Transaction("John", "Smith", "+38066565661", 1)); //'1' stands for Gender
TransactionList.ItemsSource = transactionList;
}
And a Transaction class:
public class Transaction
{
public string Name { get; set; }
public string Surname { get; set; }
public string Number { get; set; }
public int Gender { get; set; }
public string Pic { get; set; }
public Transaction(String Name, String Surname, String Number, int Gender)
{
this.Name = Name;
this.Surname = Surname;
this.Number = Number;
this.Gender = Gender;
switch (Gender)
{
case 0:
this.Pic = "Images/man.png";
break;
case 1:
this.Pic = "Images/woman.png";
break;
default:
this.Pic = "Images/unknown.png";
break;
}
}
}

The Pic property should be the type of URI not string
public Uri Pic { get; set; }
and
public Transaction(String Name, String Surname, String Number, int Gender)
{
this.Name = Name;
this.Surname = Surname;
this.Number = Number;
this.Gender = Gender;
switch (Gender)
{
case 0:
this.Pic = new Uri("Images/man.png", UriKind.Relative);
break;
case 1:
this.Pic = new Uri("Images/woman.png", UriKind.Relative);
break;
default:
this.Pic = new Uri("Images/unknown.png", UriKind.Relative);
break;
}
}
xaml
<Image Margin="2" Width="80" Height="80" Stretch="Fill" Style="{Binding}" >
<Image.Source>
<BitmapImage UriSource="{Binding Pic}" />
</Image.Source>
</Image>

Related

Xamarin CollectionView - Accessing Parent bindings in ItemTemplate?

I have the below XAML which contains a CollectionView header and associated CollectionView items. The source of the data (ItemsSource) is a list called 'users' (also shown below).
Is there anyway for me to access the properties in the top level (i.e the ones the headers are using) ?
Thanks !
<CollectionView Grid.Row="1" x:Name="users" IsGrouped="True" SelectionMode="Single">
<CollectionView.GroupHeaderTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal" MinimumHeightRequest="200" BackgroundColor="{Binding tint_colour}">
<Image Source="{Binding school_image}" WidthRequest="120" HeightRequest="100"/>
<Label Text="{Binding organisation_title}"
TextColor="{Binding font_colour}"
FontSize="Large"
FontAttributes="Bold"
VerticalTextAlignment="Center"></Label>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="HeaderTapped" CommandParameter="{Binding organisation_title}"></TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
</DataTemplate>
</CollectionView.GroupHeaderTemplate>
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" ItemSpacing="1"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout HeightRequest="200">
<Grid IsVisible="true" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<behaviors:Expander x:Name="MainExpander" CollapseAnimationLength="500" IsExpanded="false" >
<behaviors:Expander.Header>
<Grid HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<Frame HeightRequest="40" WidthRequest="40" CornerRadius="20" HorizontalOptions="Start" VerticalOptions="Center" Margin="20" Padding="0" BackgroundColor="Maroon">
<Label Text="{Binding student_initial}" TextColor="White" HorizontalOptions="Center" VerticalOptions="Center" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</Frame>
<StackLayout Grid.Column="2" HorizontalOptions="StartAndExpand" VerticalOptions="Center" Margin="20">
<Label x:Name="StudentName" Text="{Binding student_fullname}"></Label>
<Label x:Name="StudentID" IsVisible="false" Text="{Binding school_image}"></Label>
</StackLayout>
</Grid>
</behaviors:Expander.Header>
<Grid RowSpacing="0" HorizontalOptions="FillAndExpand" HeightRequest="240" VerticalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Text="Messages" Clicked="Button_Clicked"></Button>
<Button x:Name="btnTopUp" Grid.Row="1" Text="Quick Topup" Clicked="Button_Clicked" IsVisible="{Binding topup_product_id, Converter={StaticResource IsNotNullOrEmptyConverter}}"></Button>
<Button Grid.Row="2" Text="Payments" Clicked="Button_Clicked"></Button>
</Grid>
<!--TODO: Look at adding a balance for childrens topups?-->
</behaviors:Expander>
</Grid>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
This is my user ItemsSource, which is a List of AccountGroup items :
public class Account : INotifyPropertyChanged
{
public string student_unique_id { get; set; }
public string student_fullname { get; set; }
public string organisation_id { get; set; }
public string organisation_title { get; set; }
public string student_token { get;set;}
public string reg_branding_url { get;set;}
public string tint_colour { get;set;}
public string font_colour { get;set;}
public string topup_product_id { get;set;}
private string _height;
public string height
{
set { SetProperty(ref _height, value); }
get { return _height; }
}
private bool _isVisible;
public bool isVisible
{
set { SetProperty(ref _isVisible, value); }
get { return _isVisible; }
}
public string student_initial
{
get
{
return student_fullname[0].ToString();
}
}
public string school_image
{
get
{
return $"{Constants.apiBaseUrl}store/images/uploaded/mobile/{reg_branding_url}";
}
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class AccountGroup : List<Account>, INotifyPropertyChanged
{
public string organisation_title { get; set; }
public string school_image { get; set; }
public string tint_colour { get; set; }
public string font_colour { get; set; }
public List<Account> accountList { get; set; }
private bool _isVisible;
public bool isVisible
{
set { SetProperty(ref _isVisible, value); }
get { return _isVisible; }
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
public AccountGroup(string orgTitle, string orgImage, string orgTint, string orgFont, List<Account> accounts) : base(accounts)
{
organisation_title = orgTitle;
school_image = orgImage;
tint_colour = orgTint;
font_colour = orgFont;
accountList = accounts;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

How to bind image source to dynamic changable property?

I'm trzuying to show diferent images in ListView frames, depending of ServiceName in my model.
So here is my model:
public class IrrigNetModelItem
{
public int ID { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public string DateText { get; set; }
public int StationId { get; set; }
public string StationName { get; set; }
public float StationLongitude { get; set; }
public float StationLatitude { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
}
And here is part of ViewModel
public ObservableCollection<IrrigNetModelItem> IrrigNetCollection { get; set; } = new ObservableCollection<IrrigNetModelItem>();
public async void GetData()
{
base.OnAppearing();
dialog.Show();
var token = LocalData.Token;
var data = await IrrigNetService.GetServices(token, "en");
var irrigNetModel = new IrrigNetModelItem();
foreach (var d in data.items)
{
IrrigNetCollection.Add(d);
if (d.ServiceName == "irrigNET")
{
IrrigCounter++;
//FrameImage = "service_irrig_img.png";
//FrameHeaderColor = Color.FromHex("#33A8F7");
}
else
{
AlertCounter++;
//FrameImage = "alert.png";
//FrameHeaderColor = Color.FromHex("#2BB24B");
}
}
dialog.Hide();
}
For now, Service name could be "irrigNET" and "alertNET" and depending of that I want to set diferent image source in my ListView in View.
Here is View:
<ListView
ItemsSource="{Binding IrrigNetCollection}"
IsVisible="{Binding IsListVisible}"
ItemSelected="FrameList_ItemSelected"
HasUnevenRows="False"
x:Name="FrameList"
Grid.Row="2"
RowHeight="190"
Margin="0,0,0,20"
SeparatorVisibility="None"
HeightRequest="0">
<ListView.ItemTemplate Padding="0">
<DataTemplate>
<ViewCell>
<Frame
HasShadow="True"
Grid.ColumnSpan="5"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
BackgroundColor="#f4f4f4"
BorderColor="LightGray"
CornerRadius="10"
Margin="25,10,25,10"
Padding="0">
<Grid
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
IsEnabled="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="5"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="13"/>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<BoxView Color="{Binding Path=BindingContext.FrameHeaderColor, Source={x:Reference FrameList}}"
Grid.Row="0"
Grid.ColumnSpan="6"
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand"/>
<Image Source="{Binding Path=BindingContext.FrameImage, Source={x:Reference FrameList}}"
Grid.Column="1"
Grid.Row="1"
Grid.RowSpan="3"
Margin="0,20,0,0"/>
<Image Source="{Binding Path=BindingContext.FrameIcon, Source={x:Reference FrameList}}"
Grid.Column="2"
Grid.Row="1"
HorizontalOptions="Start"
VerticalOptions="Center"
HeightRequest="17"
WidthRequest="17"/>
<Label
Text="{Binding StationName}"
VerticalTextAlignment="Start"
HorizontalTextAlignment="Start"
HorizontalOptions="Start"
VerticalOptions="Center"
Margin="3,3,0,0"
FontSize="18"
Grid.Column="3"
Grid.Row="1"
FontFamily="{StaticResource BalooBhai}"
TextColor="#262f41"/>
<Image Source="service_arrow.png"
Grid.Column="4"
Grid.Row="2"
VerticalOptions="Center"
HorizontalOptions="Center"
HeightRequest="18"
WidthRequest="18"/>
<Image Source="clock.png"
Grid.Column="2"
Grid.Row="3"
HorizontalOptions="Start"
VerticalOptions="Center"/>
<Label Text="{Binding DateText}"
FontSize="14"
FontFamily="{StaticResource SegoeUIB}"
Grid.Column="3"
Grid.Row="3"
HorizontalTextAlignment="Start"
VerticalTextAlignment="Start"
Margin="3,0,0,0"
TextColor="#262f41"/>
<Label Text="{Binding Message}"
Grid.Column="3"
Grid.Row="2"
VerticalTextAlignment="Start"
HorizontalOptions="Center"
VerticalOptions="Center"
FontFamily="{StaticResource SegoeUI}" FontSize="13"
TextColor="#262f41"
Margin="0,0,10,0"/>
</Grid>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell Height="40">
<StackLayout Orientation="Horizontal"
BackgroundColor="#3498DB"
VerticalOptions="FillAndExpand">
<Label Text="TeStIrAnjE"
TextColor="White"
VerticalOptions="Center" />
<Button Text="Edit"
TextColor="White"
FontSize="20"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
</ListView>
You'll se what I tried in Image tags, but for now any image ar not show.
This is proporties that I try to use in my ViewModel:
//public string FrameIrrigImage { get; set; } //= "service_irrig_img.png";
//public Color FrameIrrigHeaderColor { get; set; } //= Color.FromHex("#33A8F7");
//public string FrameAlertImage { get; set; } //= "alert.png";
//public Color FrameAlertHeaderColor { get; set; } // = Color.FromHex("#2BB24B");
//public string typeNet { get; set; }
//public Color typeNETcolortext { get; set; }
//public Color allertNETcolortext { get; set; }
This is what I want to achive:
But this is what I get:
(As you can see BoxView heder is also diferent color blue/color but I will get it how to change it on Image example)
Also I tried to achive it using properties:
public string FrameImage { get; set; }
public Color FrameHeaderColor { get; set; }
Set them values in for loop and Bind them in xaml, but then it's all set (image and color) as for the last element in ListView
As Jason said, there are two way to do this, one is use IValueConverter by ServiceName, another is add FrameImage in model, then change FrameImage by serviceName.
I do one simple that you can take a look,if you add FrameImage in model, please implement INotifyPropertyChanged interface.
<ContentPage
x:Class="App4.Page9"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converter="clr-namespace:App4">
<ContentPage.Resources>
<converter:convert1 x:Key="converterimage" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<ListView ItemsSource="{Binding model2s}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding firstname}" />
<Image Source="{Binding imagepath}" />
<Image Source="{Binding Id, Converter={StaticResource converterimage}}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
public partial class Page9 : ContentPage
{
public ObservableCollection<model2> model2s { get; set; }
public Page9 ()
{
InitializeComponent ();
model2s = new ObservableCollection<model2>()
{
new model2(){Id=1,firstname="cherry"},
new model2(){Id=2,firstname="mattew"},
new model2(){Id=3,firstname="annine"},
new model2(){Id=4,firstname="barry"}
};
foreach(model2 m in model2s)
{
if(m.Id%2==0)
{
m.imagepath = "a1.jpg";
}
else
{
m.imagepath = "a2.jpg";
}
}
this.BindingContext = this;
}
}
public class model2:ViewModelBase
{
public int Id { get; set; }
public string firstname { get; set; }
private string _imagepath;
public string imagepath
{
get { return _imagepath; }
set
{
_imagepath = value;
RaisePropertyChanged("imagepath");
}
}
}
Converter:
class convert1 : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int id = (int)value;
if(id%2==0)
{
return "a1.jpg";
}
else
{
return "a2.jpg";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

windows phone 8 binding list inside list to the listbox

How can i bind ranking RankingInfo1 and rankinginfo 2 to the listbox. basically i am having trouble with the three level hierarchy. RankingInfo1 -> RankingInfo -> Ranking.
public class BookInfo
{
private long _BookId = 0;
public long BookId
{
get
{
return _BookId;
}
set
{
_BookId = value;
}
}
private string _BookTitle = string.Empty;
public string BookTitle
{
get
{
return _BookTitle;
}
set
{
_BookTitle = value;
}
}
public List<RankInfo> RankingInfo1 { get; set; }
public List<RankInfo> RankingInfo2 { get; set; }
}
public class RankInfo {
public int? Ranking { get; set; }
public DateTime? WeekDate { get ; set ;}
}
what i have tried but the thing is that i am getting : booklocator.Model.RankInfo as the output.
<ListBox x:Name="lstrankingUSAToday" ItemsSource="{Binding RankingInfo1}" Grid.ColumnSpan="2">
<StackPanel Width="Auto">
<TextBlock Text="Ranked USA Today: "/>
<TextBlock Text="{Binding Ranking}"></TextBlock>
</StackPanel>
</ListBox>
You need to use ItemsControl to bind the list of values. I am showing simple demo try it and let me if you need further help.
XAML
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding BookId}" FontSize="20" />
<TextBlock Text="{Binding BookTitle}" FontSize="20" />
<ItemsControl ItemsSource="{Binding RankingInfo1}" Margin="0 20 0 0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Blue" BorderThickness="2">
<TextBlock Text="{Binding Ranking}" FontSize="20" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding RankingInfo2}" Margin="0 20 0 0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="2">
<TextBlock Text="{Binding Ranking}" FontSize="20" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#
public List<BookInfo> Items { get; set; }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var _RankingInfo1 = new List<RankInfo>
{
new RankInfo { Ranking = 1, WeekDate = DateTime.Now },
new RankInfo { Ranking = 2, WeekDate = DateTime.Now }
};
var _RankingInfo2 = new List<RankInfo>
{
new RankInfo { Ranking = 10, WeekDate = DateTime.Now.AddDays(-2) },
new RankInfo { Ranking = 20, WeekDate = DateTime.Now.AddDays(-2) }
};
Items = new List<BookInfo>
{
new BookInfo { BookId = 9, BookTitle = "My Book Title", RankingInfo1 = _RankingInfo1, RankingInfo2 = _RankingInfo2 }
};
this.DataContext = this;
}

windows store app how to get back values from databinded usercontroles

how can i get back values from data binder view elements
am using a list view and data binded it to collection
<ListView.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid Height="20" Width="100" Background="#FFF5F3F3" Tapped="Grid_Tapped">
<TextBlock Text="{Binding Name}" Foreground="#FF0E0303"/>
<TextBlock Text="{Binding Age}" Foreground="#FF0E0303"/>
</Grid>
</DataTemplate>
now what i want is get the values back at gridtapped event
Try this
<ListView x:Name="lv" IsItemClickEnabled="True" ItemClick="lv_ItemClick_1">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="20" Width="100" Background="#FFF5F3F3">
<TextBlock Text="{Binding Name}" Foreground="#FF0E0303"/>
<TextBlock Text="{Binding Age}" Foreground="#FF0E0303"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
lv.ItemsSource = new List<Person>
{
new Person("Charles", 25),
new Person("Mark", 27),
new Person("John", 22),
};
}
private void lv_ItemClick_1(object sender, ItemClickEventArgs e)
{
var objPerson = (Person)e.ClickedItem;
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

xaml: Can't get image binding to work

I'm trying to do some databinding, but I can't get the image to show. This is what the xaml looks like:
<ListBox Name="tListBox" Margin="0,0,-12,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<Image Source="{Binding imgUri}" Margin="2" Height="100" Width="100" />
<!--<Image Source="images/weapons/tmp.png" Height="100" Width="100" />-->
<StackPanel Width="311">
<TextBlock Text="{Binding wName}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
<TextBlock Text="{Binding price}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is what the codebehind looks like:
public partial class MainPage : PhoneApplicationPage
{
List<Weapon> tList;
List<Weapon> cList;
List<Weapon> eList;
// Constructor
public MainPage()
{
InitializeComponent();
loadData();
}
public void loadData()
{
tList = new List<Weapon>();
tList.Add(new Weapon
{
wName = "Glock 18",
imageUri = "images/weapons/glock18.png",
price = "$400"
});
tList.Add(new Weapon
{
wName = "USP tactical",
imageUri = "images/weapons/usptactical.png",
price = "$500",
});
tListBox.ItemsSource = tList;
}
}
public class Weapon
{
public string wName { get; set; }
public string imageUri { get; set; }
public string price { get; set; }
}
When running this the name and price gets shown, but not the image. The line that is commented out in the xaml works, can anyone please correct what am I doing wrong?
Found the mistake. imgUri in the xaml and imageUri in the codebehind - different variable names. Quite embarrassing ;)