Download image in windows phone 8.1 - windows-phone-8.1

i want to download images from specified Uri s and show it in Grid View
<GridView>
<GridView.ItemTemplate>
<DataTemplate>
<Image Width="150" Height="150" Source="{Binding Source={}}"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>

If you have a model class, set the following property & bind it to the image element.
Public class YourClass
{
public string imageuri { get ; set ; } //web image uri
public BitmapImage ImageUrl
{
get
{
if (!string.IsNullOrEmpty(imageuri))
{
BitmapImage bmi = new BitmapImage();
bmi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bmi.UriSource = new Uri(imageuri, UriKind.Absolute);
return bmi;
}
return null;
}
}
}
<GridView>
<GridView.ItemTemplate>
<DataTemplate>
<Image Width="150" Height="150" Source="{Binding ImageUrl,Mode=Twoway}"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>

Related

MVVMcross Command Binding fire Exception

I experience an issue when i try to use a command to open a Second View Model V4.0.Beta5.
I followed the Exemple described in N+1 Video series https://www.youtube.com/playlist?list=PLR6WI6W1JdeYSXLbm58jwAKYT7RQR31-W
First ViewModel
public class FirstViewModel
: MvxViewModel
{
private string _hello = "Hello MvvmCross";
public string Hello
{
get { return _hello; }
set
{
_hello = value;
RaisePropertyChanged(() => Hello);
}
}
private Cirrious.MvvmCross.ViewModels.MvxCommand _goSecondViewCommand;
public System.Windows.Input.ICommand GoSecondViewCommand
{
get
{
_goSecondViewCommand = _goSecondViewCommand ??
new Cirrious.MvvmCross.ViewModels.MvxCommand(DoGoSecondView);
return _goSecondViewCommand;
}
}
private void DoGoSecondView()
{
base.ShowViewModel<SecondViewModel>();
}
}
Second View model
public class SecondViewModel :MvxViewModel
{
private string _hello2 = "Hello2 MvvmCross";
public string Hello2
{
get { return _hello2; }
set
{
_hello2 = value;
RaisePropertyChanged(() => Hello2);
}
}
}
First View
<views:MvxWindowsPage
x:Class="TestCommand.UWP.Views.FirstView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestCommand.UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:Cirrious.MvvmCross.WindowsUWP.Views"
mc:Ignorable="d">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="70,92,0,0" TextWrapping="Wrap" Text="FirstView" VerticalAlignment="Top" Width="223"/>
<Button x:Name="button" Command="{Binding GoSecondViewCommand}" Content="Button" HorizontalAlignment="Left" Height="108" Margin="70,346,0,0" VerticalAlignment="Top" Width="223"/>
</Grid>
Second view
<views:MvxWindowsPage
x:Class="TestCommand.UWP.Views.SecondView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestCommand.UWP.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:Cirrious.MvvmCross.WindowsUWP.Views"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid />
Setup Class:
public class Setup : MvxWindowsSetup
{
public Setup(Frame rootFrame) : base(rootFrame)
{
}
protected override IMvxApplication CreateApp()
{
return new TestCommand.Core.App();
}
}
If you want you can download the solution Here:
https://onedrive.live.com/redir?resid=A5D9789788DE33CB!36079&authkey=!AKs9nsG28iI6nQQ&ithint=file%2czip.
The possible reason is you don't use Setup correctly in your UWP app, here is what I do to make this work:
1) Create two ViewModels in the UWP app: FirstViewModel and SecondViewModel
2) Create a Setup class in Setup.cs file:
public class Setup : MvxWindowsSetup
{
public Setup(Frame rootFrame) : base(rootFrame)
{
}
protected override IMvxApplication CreateApp()
{
return new AppSetup();
}
}
public class AppSetup : MvxApplication
{
public override void Initialize()
{
RegisterAppStart<FirstViewModel>();
}
}
3) FirstView.xaml:
<StackPanel>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="70,92,0,0" TextWrapping="Wrap" Text="FirstView" VerticalAlignment="Top" Width="223"/>
<TextBlock Height="50" Text="{Binding Hello}" />
<Button x:Name="button" Command="{Binding GoSecondViewCommand}" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="223" Height="50" />
</StackPanel>
4) SecondView.xaml:
<StackPanel>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Margin="70,92,0,0" TextWrapping="Wrap" Text="SecondView" VerticalAlignment="Top" Width="223"/>
<TextBlock Height="50" Text="{Binding Hello2}" />
</StackPanel>
5) In App.xaml.cs file, make the following changes in OnLaunched method:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
......
if (rootFrame.Content == null)
{
var setup = new Setup(rootFrame);
setup.Initialize();
var start = Mvx.Resolve<IMvxAppStart>();
start.Start();
}
// Ensure the current window is active
Window.Current.Activate();
}
By the way, the MvvmCross version is 3.5.1
Check the Completed sample on Github
Update for exception in OnNavigationFailed method:
Please comment this line in FirstView and SecondView's code behind:
ViewModel = new FirstViewModel();
ViewModel = new SecondViewModel();
The MvvmCross has set the ViewModel automatically.

Using FlipView to create TabControl in Metro Apps

i'm currently creating a Metro Style Application and want to use the FlipView control to work like the tab control in WPF and winforms, please can any one help me ?
You would put FlipViewItems in the FlipView the same way you'd put TabItems in a TabControl. To add tabs - you could have a StackPanel with TextRadioButtonStyled RadioButtons that have their check states synchronized with the FlipView selection state. Alternatively you could have a heavily styled ListView for the headers bar.
i solved it by editing the flipviewitem template and making its view like the wanted tab page view. Then i added a button on the top of every item to activate it.
We don't have Tab Control in WP8.1 but we can customize using FlipView. Flip View has a property selected index so we can set which view we want.
Create a xaml page, for example MainPage.xaml
For Tab Header
<Border BorderThickness="0,0,0,1" BorderBrush="White" >
<Grid Grid.Row="0" Background="Black" x:Name="navigateHead" >
<TextBlock x:Name="appbarSports" Text="Sports" Tapped="appbarSports_Tapped" TextAlignment="Center" Width="80" Margin="0,34,320,7" />
<TextBlock x:Name="appbarCars" Text="Cars" Tapped="appbarCars_Tapped" Margin="160,34,160,7" TextAlignment="Center" />
<TextBlock x:Name="appbarHomes" Text="Homes" Tapped="appbarHomes_Tapped" Margin="80,34,240,7" TextAlignment="Center" />
<Image x:Name="imgLine0" Source="ms-appx:///Images/white.png" Width="80" Height="3" Stretch="Fill" Margin="0,55,320,1" ></Image>
<Image x:Name="imgLine1" Source="ms-appx:///Images/white.png" Width="80" Height="3" Stretch="Fill" Margin="81,55,239,1" Visibility="Collapsed" />
<Image x:Name="imgLine2" Source="ms-appx:///Images/white.png" Width="80" Height="3" Stretch="Fill" Margin="162,55,158,1" Visibility="Collapsed" />
</Grid>
</Border>
For Flip view XAML code is
<Grid Grid.Row="1" >
<FlipView x:Name="flipControl" SelectionChanged="flipControl_SelectionChanged" >
<FlipViewItem >
<ListView x:Name="listViewForSports" >
<ListView.ItemTemplate>
<DataTemplate>
<Image Stretch="Fill" Source="{Binding SportsImage}"></Image>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</FlipViewItem>
<FlipViewItem >
<ListView x:Name="listViewForHomes">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding HomesImage}" Stretch="Fill"></Image>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</FlipViewItem>
<FlipViewItem >
<ListView x:Name="listViewForCars">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding CarsImage}" Stretch="Fill"></Image>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</FlipViewItem>
</FlipView>
</Grid>`
and write in code behind file MainPage.xaml.cs
Just initialize these globally:
public sealed partial class MainPage : Page
{
List<Sports> listOfSports;
List<Cars> listOfCars;
List<Homes> listOfHomes;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
bind data to the FlipView control when page is initialized
protected override void OnNavigatedTo(NavigationEventArgs e)
{
flipControl.SelectedIndex = 0;
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
GetData();
}
This method will bind
public void GetData()
{
listOfSports = new List<Sports>();
for (int i = 1; i < 9; i++)
{
listOfSports.Add(new Sports() { SportsImage = #"ms-appx:///Images/Sports/image" + i.ToString() + ".jpg" });
}
listViewForSports.ItemsSource = listOfSports;
listOfCars = new List<Cars>();
for (int i = 1; i < 14; i++)
{
listOfCars.Add(new Cars() { CarsImage = #"ms-appx:///Images/Cars/image" + i.ToString() + ".jpg" });
}
listViewForCars.ItemsSource = listOfCars;
listOfHomes = new List<Homes>();
for (int i = 1; i < 9; i++)
{
listOfHomes.Add(new Homes() { HomesImage = #"ms-appx:///Images/Homes/image" + i.ToString() + ".jpg" });
}
listViewForHomes.ItemsSource = listOfHomes;
}
public class Cars
{
public string CarsImage { get; set; }
}
public class Sports
{
public string SportsImage { get; set; }
}
public class Homes
{
public string HomesImage { get; set; }
}`
I did with tap event to navigation withing flip view` private void appbarSports_Tapped(object sender, TappedRoutedEventArgs e)
{
// TextBlock a = sender as TextBlock;
// imgLine0.Margin = new Thickness(a.Margin.Left, 55, a.Margin.Right, 1);
flipControl.SelectedIndex = 0;
method(0);
}
private void appbarCars_Tapped(object sender, TappedRoutedEventArgs e)
{
// TextBlock a = sender as TextBlock;
//imgLine0.Margin = new Thickness(a.Margin.Left, 55, a.Margin.Right, 1);
flipControl.SelectedIndex = 2;
method(2);
}
private void appbarHomes_Tapped(object sender, TappedRoutedEventArgs e)
{
// TextBlock a = sender as TextBlock;
// imgLine0.Margin = new Thickness(a.Margin.Left, 55, a.Margin.Right, 1);
flipControl.SelectedIndex = 1;
method(1);
}
I also used for when the user flips so I used FlipView.SelectionChanged event
private void flipControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FlipView viewControl = sender as FlipView;
int a = viewControl.SelectedIndex;
method(a);
}
This method() is help full for changing imageLine position
public void method(int a)
{
if (imgLine0 != null)
{
switch (a)
{
case 0:
imgLine0.Visibility = Visibility.Visible;
imgLine1.Visibility = Visibility.Collapsed;
imgLine2.Visibility = Visibility.Collapsed;
break;
case 1:
imgLine0.Visibility = Visibility.Collapsed;
imgLine1.Visibility = Visibility.Visible;
imgLine2.Visibility = Visibility.Collapsed;
break;
case 2:
imgLine0.Visibility = Visibility.Collapsed;
imgLine1.Visibility = Visibility.Collapsed;
imgLine2.Visibility = Visibility.Visible;
break;
}
}
}

Design Time Windows Store App with JSON

I am trying to create a windows store app using a Blank Windows 8 store App and can't get basic Design time working. I am obviously missing something simple, but with the research I have done don't see the difference
Here is my MainPage.xaml
<Page
x:Class="TestHubDataBinding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestHubDataBinding"
xmlns:data="using:TestHubDataBinding.ViewModels"
xmlns:repo="using:TestHubDataBinding.Repo"
d:DataContext="{Binding Source={d:DesignData Source=Repo/VacationData.json, IsDesignTimeCreatable=True, Type=data:VacationViewModel}}"
xmlns:viewModel="using:TestHubDataBinding.Repo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Hub x:Name="MainHub" d:DataContext="{ Binding VacationViewModel[0], Source={d:DesignData Source=Repo/VacationData.json, IsDesignTimeCreatable=True, Type=repo:VacationDataSource}}">
<HubSection x:Name="VacationItemsSection" Width="500" Height="500" x:Uid="VacationItemsSection" Header="Vacations">
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Style="{StaticResource SubheaderTextBlockStyle}" Grid.Row="1" Margin="0,10,0,0" TextWrapping ="Wrap"
Text="{Binding VacationViewModel[0].Name, Mode=OneWay}" />
</Grid>
</DataTemplate>
</HubSection>
</Hub>
</Grid>
Here is my View Model:
[DataContract]
public class VacationViewModel
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<string> VacationsList { get; set; }
}
Here is my JSON:
[
{
"Name":"Virginia Beach",
"VItems":
[
{
"Name":"Shorts (Plad)","Value":"2"
}
]
}
, {
"Name":"Orlando Florida",
"VItems":
[
{
"Name":"Shorts (Plad)","Value":"2"
}
]
}
]
And Here is my DataSource:
public class VacationDataSource
{
private readonly ObservableCollection<VacationViewModel> _vacations = new ObservableCollection<VacationViewModel>();
public ObservableCollection<VacationViewModel> Vacations
{
get { return _vacations; }
}
public async Task<TModel> ToObject<TModel>()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///DataModel/Repo/VacationData.json"));
var json = await FileIO.ReadTextAsync(file);
return Deserialize<TModel>(json);
}
public string ToJson<TObject>(TObject model)
{
return Serialize(model);
}
private static string Serialize<TObject>(TObject model, JsonSerializerSettings settings = null)
{
if (settings == null)
{
settings = new JsonSerializerSettings();
}
return JsonConvert.SerializeObject(model, settings);
}
private static TModel Deserialize<TModel>(string jsonString, JsonSerializerSettings settings = null)
{
if (settings == null)
{
settings = new JsonSerializerSettings();
}
return JsonConvert.DeserializeObject<TModel>(jsonString, settings);
}
}
It seems that the data will return for runtime, but design time just does not want to work.
Thanks

WP8 get URI of images in MediaLibrary

As I am using my own LongListSelector to let the user select from an image I need to retrieve the URI's of all images in the Medialibrary. I couldn't find any possibility to do this yet.
All I have seen what is possible is to get the name of the image:
MediaLibrary m = new MediaLibrary();
foreach (var r in m.Pictures)
{
Stream imageStream = r.GetImage();
}
How can I get the rest of the path?
EDIT
Following the first solution:
Gallery.xaml
<phone:LongListSelector
x:Name="GalleryLLS"
LayoutMode="Grid"
GridCellSize="108,108"
SelectionChanged="GalleryLLS_SelectionChanged"
Margin="0,0,144,12"
ItemsSource="{Binding ListOfImages}" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Width="150" Height="150"
Source="{Binding}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
Gallery.xaml.cs
private List<WriteableBitmap> _listOfImages = new List<WriteableBitmap>();
public List<WriteableBitmap> ListOfImages
{
get { return _listOfImages; }
set { _listOfImages = value; }
}
public Gallery()
{
InitializeComponent();
var ml = new MediaLibrary();
var Pictures = ml.Pictures;
foreach (var item in Pictures)
{
ListOfImages.Add(PictureDecoder.DecodeJpeg(item.GetImage()));
}
}
results in not showing images. Debugger shows that imageas are added correctly to my list but I won't see anything.
It seems that the API doesn't exposes URI property for pictures returned from Media Library. So you need to do it with different approach. For example, you can have a list of WritableBitmaps instead of list of URIs :
private List<WriteableBitmap> _listOfImages = new List<WriteableBitmap>();
public List<WriteableBitmap> ListOfImages
{
get { return _listOfImages; }
set { _listOfImages = value; }
}
.......
.......
var ml = new MediaLibrary();
var Pictures = ml.Pictures;
foreach (var item in Pictures)
{
ListOfImages.Add(PictureDecoder.DecodeJpeg(item.GetImage()));
}
........
//in XAML
<phone:LongListSelector ItemsSource="{Binding ListOfImages}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Width="150" Height="150"
Source="{Binding}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
........
</phone:LongListSelector>
........
[Codes adapted from http://www.neelesh-vishwakarma.com]
Why do you need the path? To show the image? If you just need to show the image in the list as a thumbnail, you can use the stream to create a BitmapImage:
var bi = new BitmapImage();
bi.SetSource(r.GetThumbnail());
Now you can set that bi as a Image.Source.

Why there is no PlaceHolder like property in XAML TextBox

Is there any "placeholder type" property availble for textbox in xaml in windows phone 8
There is the PhoneTextBox in the official Windows Phone Toolkit, covered here.
Sample code:
<toolkit:PhoneTextBox Hint="Password"/>
To add toolkit to your project :
Type the following into your package manager console :
PM> Install-Package WPtoolkit
And
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
inside <phone:PhoneApplicationPage tag in the xaml page
Try like this below code:
<TextBox x:Name="InvoiceDate" Text="" Width="300" TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" />
<TextBlock IsHitTestVisible="False" Text="Men att läsa" Width="300" TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" Padding="5, 5, 5, 5" Foreground="LightGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=InvoiceDate}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
There is no placeholder property for TextBox. I use the following solution to work around this for a username textbox:
XAML:
<Grid>
<TextBlock Name="UsernamePlaceholder" Text="Username" />
<TextBox Name="UsernameTextBox" Text="" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
</Grid>
Code:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
UsernamePlaceholder.Visibility = Visibility.Collapsed;
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
var textbox = sender as TextBox;
if (string.IsNullOrEmpty(textbox.Text))
{
UsernamePlaceholder.Visibility = Visibility.Visible;
}
}
}
This basically replaces the TextBox with a Grid-element, containing a TextBox and a TextBlock (working as placeholder). Then when the textbox is focused, the textblock is hidden, and when it looses focus the textblock is shown if the textbox is empty.
My solution is based on the answer of PKENO
XAML (UserControl):
<UserControl x:Class="FestivalProject.Controls.TextBoxPH"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<TextBox x:Name="testTextBox" Margin="0" LostFocus="testTextBox_LostFocus" GotFocus="testTextBox_GotFocus"/>
</UserControl>
Code behind UserControl:
public partial class TextBoxPH : UserControl
{
private String _Text;
public String Text
{
get { return _Text; }
set {
_Text = testTextBox.Text = value;
}
}
private String _PlaceHolder;
public String PlaceHolder
{
get { return _PlaceHolder; }
set {
_PlaceHolder =testTextBox.Text = value;
}
}
public TextBoxPH()
{
InitializeComponent();
}
private void testTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(testTextBox.Text)) testTextBox.Text = PlaceHolder;
}
private void testTextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (testTextBox.Text.Equals(PlaceHolder, StringComparison.OrdinalIgnoreCase)) testTextBox.Text = string.Empty;
}
}
XAML (in Window):
<txtPH:TextBoxPH Margin="5" Grid.ColumnSpan="2" PlaceHolder="PlaceholderText"/>
Probably not the most efficient way, but it works.