How to change pivot header into page number? - windows-phone-7

I have a pivot control, the items are binded from a list, I want to make the pivot header look like a page number, look like this : (1/20) (2/20) (3/20) .... This is my xaml:
<Grid x:Name="LayoutRoot">
<Grid.Background>
<ImageBrush ImageSource="/Images/PivotBackground.png"/>
</Grid.Background>
<!--Pivot Control-->
<controls:Pivot x:Name="newsPivot" ItemsSource="{Binding LatestArticles}" Margin="0,68,0,0">
<!--Pivot item one-->
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="1" FontSize="30" Foreground="White" TextWrapping="Wrap"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
<controls:Pivot.ItemTemplate>
<DataTemplate>
<ScrollViewer>
<Grid>
<StackPanel>
<TextBlock Text="{Binding title}" FontSize="30" Foreground="Black" TextWrapping="Wrap"
Grid.Row="1"
Grid.Column="0"
Width="425"
Margin="10,0,0,0"/>
</StackPanel>
<StackPanel>
<Image delay:LowProfileImageLoader.UriSource="{Binding thumbnail, StringFormat='http://digitaledition.philstar.com/newsrepository/newsarticles/thumbs/images/\{0\}'}"
Margin="18,100,0,0"
Grid.Column="0"
Grid.Row="2"
HorizontalAlignment="Left"
Width="150"
Height="175"
Stretch="UniformToFill" />
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding author, StringFormat='By \{0\}'}" TextWrapping="Wrap" FontSize="22"
Grid.Column="1"
Width="220"
Foreground="Gray"
Margin="120,135,0,0"/>
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding dateFormatted}" TextWrapping="Wrap" FontSize="20"
Grid.Column="1"
Width="240"
Foreground="Gray"
Margin="140,210,0,0"/>
</StackPanel>
<StackPanel>
<TextBlock Text="{Binding content}" TextWrapping="Wrap" FontSize="24"
Grid.Column="1"
Width="425"
Foreground="Black"
Margin="10,325,0,0"/>
</StackPanel>
</Grid>
</ScrollViewer>
</DataTemplate>
</controls:Pivot.ItemTemplate>
<!--Pivot item two-->
</controls:Pivot>
</Grid>
Spent hours of searching on google but no solution found. Please someone help me with my project. thanks in advance!
Code behind Xaml:
public NewsPivot()
{
InitializeComponent();
var y = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(y, "DownloadStringCompleted")
.Subscribe(r =>
{
var des =
JsonConvert.DeserializeObject<List<LatestArticles>>(r.EventArgs.Result);
newsPivot.ItemsSource = des.Where(s=> s.category_id == "1");
});
y.DownloadStringAsync(
new Uri("http://sample.json.com/mobile/articles?"));
}
LatestArticle.cs :
public class LatestArticles
{
public string id { get; set; }
public string title { get; set; }
public string thumbnail { get; set; }
public string hits { get; set; }
public string thumbCaption { get; set; }
public string category_id { get; set; }
public string dateFormatted { get; set; }
public string author { get; set; }
}

You would have to Bind the Text of the Header to a property on your Articles object. This propery would be the page index of the article.
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding PageNumber}" FontSize="30" Foreground="White" TextWrapping="Wrap"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
You would then need to set the page number of the Article when it is added to the LatestArticles collection.
LatestArticles.Add(article);
article.PageNumber = LatestArticles.Count +1;
Another option is to use a value converter. This option would require you to have access to the LatestArticles somehow.
<controls:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource PageNumberConverter}}" FontSize="30" Foreground="White" TextWrapping="Wrap"/>
</DataTemplate>
</controls:Pivot.HeaderTemplate>
The ValueConverter is very simple
public class PageNumberConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Assumes that the App.xaml.cs class has a static ViewModel property
return App.ViewModel.LatestArticles.IndexOf(value) + 1;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Related

How do I bind to a validation rule in XAML

I am following the example given here:
https://social.technet.microsoft.com/wiki/contents/articles/31422.wpf-passing-a-data-bound-value-to-a-validation-rule.aspx
I get the exception at the following line in my DataTemplateSelector:
return element.FindResource("MinParameterDataTemplateThin") as DataTemplate;
"Unexpected record in Baml stream. Trying to add to MaximumValueValidation which is not a collection or has a TypeConverter."
Code:
public class BindingProxy : System.Windows.Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get => (object)GetValue(DataProperty);
set => SetValue(DataProperty, value);
}
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new PropertyMetadata(null));
}
public class MaxValueWrapper : DependencyObject
{
public static readonly DependencyProperty MaxValueProperty =
DependencyProperty.Register("MaxValue", typeof(double),
typeof(MaxValueWrapper), new FrameworkPropertyMetadata(double.MaxValue));
public int MaxValue
{
get => (int)GetValue(MaxValueProperty);
set => SetValue(MaxValueProperty, value);
}
}
public class MaximumValueValidation : ValidationRule
{
public MaxValueWrapper MaxValueWrapper { get; set; }
/// <summary>
/// validate whether the input value is in range
/// </summary>
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
try
{
if (value != null && ((string)value).Length > 0)
{
double userInput = double.Parse((string)value);
if (userInput > MaxValueWrapper.MaxValue)
return new ValidationResult(false,
"Please enter a value <= Max " + MaxValueWrapper.MaxValue);
}
}
catch (Exception e)
{
return new ValidationResult(false, $"Invalid characters or {e.Message}");
}
return ValidationResult.ValidResult;
}
}
XAML:
<DataTemplate x:Key="MinParameterDataTemplateThin">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="120"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding DisplayName, StringFormat='{}{0}:'}" Grid.Column="0" Margin="10,5,5,10" VerticalAlignment="Top" TextWrapping="Wrap"
Visibility="{Binding Visibility}" ToolTipService.ShowDuration="20000">
<TextBlock.ToolTip>
<ToolTip DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={x:Static RelativeSource.Self}}">
<TextBlock Text="{Binding Description}"/>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBox Margin="5" Width="50" VerticalAlignment="Top"
Visibility="{Binding Visibility}" IsEnabled="{Binding IsEnabled}">
<i:Interaction.Behaviors>
<utilities:SelectTextOfTextBox/>
</i:Interaction.Behaviors>
<TextBox.Resources>
<validations:BindingProxy x:Key="proxy" Data="{Binding}"/>
</TextBox.Resources>
<TextBox.Text>
<Binding Path="{Binding DefaultValue, StringFormat=N2}" Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnExceptions="True"
NotifyOnValidationError="True"
ValidatesOnNotifyDataErrors="True">
<Binding.ValidationRules>
<validations:MaximumValueValidation ValidatesOnTargetUpdated="True">
<validations:MaximumValueValidation.MaxValueWrapper>
<validations:MaxValueWrapper MaxValue="{Binding Data.MaxValue, Source={StaticResource proxy}}"/>
</validations:MaximumValueValidation.MaxValueWrapper>
</validations:MaximumValueValidation>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBlock Text="{Binding UnitSymbol}" Margin="5" VerticalAlignment="Top" Visibility="{Binding Visibility}"/>
</StackPanel>
</Grid>
</DataTemplate>
I have several working DataTemplates like this one, but they do not use validation rules with the TextBox. Perhaps I am not following the wiki example correctly, but I am not seeing the problem, and I don't understand the exception.
EDIT:
After staring at the exception message, it occurs to me that the "outer" DataTemplate might be relevant, but I cannot be sure. The DataTemplate above is for a WorkflowParameter object, which is part of a Collection nested in a parent WorkflowParameter object. The DataTemplate for this parent is:
<DataTemplate x:Key="GroupedInversionParameterDataTemplate">
<Grid Visibility="{Binding Visibility}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="800"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding DisplayName, StringFormat='{}{0}:'}" Grid.Column="0" Margin="5" VerticalAlignment="Top" TextWrapping="Wrap"
Visibility="{Binding Visibility}" ToolTipService.ShowDuration="20000">
<TextBlock.ToolTip>
<ToolTip DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={x:Static RelativeSource.Self}}">
<TextBlock Text="{Binding Description}"/>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
<ItemsControl ItemsSource="{Binding GroupedWorkflowParameters}" Grid.Column="1"
ItemTemplateSelector="{StaticResource WorkflowParameterTemplateSelector}"
IsTabStop="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Visibility" Value="{Binding Visibility}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Grid>
</DataTemplate>
The mention of trying to add a collection, in the exception message, made me think that the ItemsControl in this outer template could be a problem. I would not expect it to be an issue, but maybe I am missing something.
I though the problem as with the validation XAML, so I commented it out and found there was still an exception. This snippet of XAML:
<Binding Path="{Binding DefaultValue, StringFormat=N2}"
had to change to
<Binding Path="DefaultValue" StringFormat="N2"

Deserializing a JSON array to LongListSelector Windows Phone 8

How can i deserialize this jsonx variable and put it on a longlistselector on windows phone?
Currently i can only echo one string with messagebox. i need key-value sets on a longlistselector.
edit: this is my answer http://pastebin.com/CcADHaab
here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp5.Resources;
using Newtonsoft.Json;
namespace PhoneApp5
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z'
}";
string jsonx = #"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
// Console.WriteLine(account.Email);
// james#example.com
MessageBox.Show(account.Email);
list.ItemsSource = new BookList();
}
}
public class BookList : List<Account>
{
public BookList()
{
}
}
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
// public IList<string> Roles { get; set; }
}
///////////////////////////
}
and my XAML
<phone:PhoneApplicationPage
x:Class="PhoneApp5.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector Name="list">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding id}" />
<TextBlock Text=" ( " />
<TextBlock Text="{Binding item}" FontStyle="Italic" />
<TextBlock Text=" )" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
You need a class to represent your json:
public class MyClass
{
public string Id { get; set; }
public string Item { get; set; }
}
Set a ObservableCollection property in your Form:
public ObservableCollection<MyClass> MyClassCollection { get; set; }
and then set the MyClassCollection property to your Deserialized json
MyClassCollection = JsonConvert.DeserializeObject<ObservableCollection<MyClass>>(e.Result);
That way you're binding your class list to the LongListSelector Control in your XAML:
<phone:LongListSelector Name="list" ItemsSource="{Binding MyClassCollection}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding id}" />
<TextBlock Text=" ( " />
<TextBlock Text="{Binding item}" FontStyle="Italic" />
<TextBlock Text=" )" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
That should work.

Windows Phone 7 MVVM databinding form

I'm new to Windows Phone development, and currently have a simple form. I'm using the MVVM pattern and MvvmLight to run a command. The "Applicant" entity is always empty, and it looks like the 2 way databinding isn't working. Here is my code, I hope someone can point me in the right direction.
View
<Grid x:Name="LayoutRoot" Background="Transparent" DataContext="{Binding Applicant}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="create account" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<StackPanel>
<TextBlock FontSize="15" TextWrapping="Wrap" Margin="0,0,0,10" Text="Please register to create your applicant account. No information will be passed to third parties for any reason."></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Forename" Width="100"></TextBlock>
<TextBox Width="350" BorderBrush="Red" DataContext="{Binding Forename, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Surname" Width="100"></TextBlock>
<TextBox Width="350" x:Name="Surname" BorderBrush="Red" DataContext="{Binding Surname, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Email" Width="100"></TextBlock>
<TextBox Width="350" x:Name="EmailAddress" BorderBrush="Red" DataContext="{Binding EmailAddress, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Password" Width="100"></TextBlock>
<PasswordBox Width="350" x:Name="PassPhrase" BorderBrush="Red" DataContext="{Binding PassPhrase, Mode=TwoWay}"></PasswordBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="City" Width="100"></TextBlock>
<TextBox Width="350" x:Name="City" DataContext="{Binding City, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="State" Width="100"></TextBlock>
<TextBox Width="350" x:Name="County" DataContext="{Binding County, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Country" Width="100"></TextBlock>
<TextBox Width="350" x:Name="Country" DataContext="{Binding Country, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel>
<Button Name="btnContact"
Content="Register"
DataContext="{Binding ElementName=this, Path=DataContext}"
Command="{Binding SaveApplicantCommand}"
Width="300"/>
</StackPanel>
</StackPanel>
</Grid>
</Grid>
View code behind
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ApplicantViewModel vm = new ApplicantViewModel();
DataContext = vm;
}
View Model (the view model inherits from ViewModelBase which implements INotifyPropertyChanged)
public class ApplicantViewModel : ViewModelBase
{
public ApplicantViewModel()
{
SaveApplicantCommand = new RelayCommand(SaveApplicant);
Applicant = new Applicant();
}
public ICommand SaveApplicantCommand {get; set;}
void SaveApplicant()
{
if (string.IsNullOrEmpty(Applicant.Forename))
{
MessageBox.Show("Please enter a forename", "Oops...", MessageBoxButton.OK);
return;
}
db.AddObject("Applicants", Applicant);
db.BeginSaveChanges(OnChangesSaved, db);
}
void OnChangesSaved(IAsyncResult result)
{
}
private Applicant _applicant;
public Applicant Applicant
{
get
{
return _applicant;
}
set
{
if (_applicant != value)
{
_applicant = value;
RaisePropertyChanged("Applicant");
}
}
}
}
Whatever is entered into the Forename text box, I always get the error message because Forename is null.
***** UPDATE *********
Here is the Forename property in the model
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
public string Forename
{
get
{
return this._Forename;
}
set
{
this.OnForenameChanging(value);
this._Forename = value;
this.OnForenameChanged();
this.OnPropertyChanged("Forename");
}
}
An ApplicantViewModel does not have a Forename property. Only Applicant has. So do the following:
<TextBox Width="350" BorderBrush="Red"
DataContext="{Binding Applicant.Forename, Mode=TwoWay}"/>
do the same with the other text boxes.

Display app setting in a WP7 ListBox control

I have a ListBox control which is binded to a ObservableCollection.
My XAML code:
<ListBox Margin="12,148,12,90" ItemsSource="{Binding FuelRecords}" Name="ListBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Fuel quantity: {Binding Quantity}" FontSize="20" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I want to display a unit of measure (litre, gallon), after the quantity. The measurement unit is saved using IsolatedStorageSettings in the AppSettings class (VolumeSettingproperty).
End result:
Fuel quantity: 23.45 gallon
public class Fuel
{
public double QuantityGallons { get; set; }
public double Quantity
{
get
{
return QuantityGallons * (AppSettings["VolumeSetting"] == Units.Pounds) ? 1.5 : 1.0;
}
}
public string Units
{
get
{
return (AppSettings["VolumeSetting"] == Units.Pounds) ? "pound" : "gallon";
}
}
}
xaml:
<StackPanel Orientation="Horizontal">
<TextBlock Text="Fuel quantity: " FontSize="20" />
<TextBlock Text="{Binding Quantity}" FontSize="20" />
<TextBlock Text="{Binding Units}" FontSize="20" />
</StackPanel>

Windows Phone 7 - Images & Themes in a databound listbox

I have a listbox that I'm doing some databinding. As you can see I have some images associated with the data that I'm displaying... Everything is working great, except that when I change themes I need to change my image to the black images. I can't seem to figure out how to change the images when they are bound like this.
Any ideas?
<ListBox x:Name="lbPharm" ItemsSource="{Binding col}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="DataTemplateStackPanel" Orientation="Horizontal">
<TextBlock FontFamily="Segoe WP Semibold" FontWeight="Bold" FontSize="30" VerticalAlignment="Top" Margin="20,10">*</TextBlock>
<StackPanel>
<TextBlock x:Name="ItemText" Text="{Binding name}" FontSize="{StaticResource PhoneFontSizeLarge}"/>
<TextBlock x:Name="ItemNumber" Text="{Binding number}" FontSize="{StaticResource PhoneFontSizeNormal}"/>
</StackPanel>
<Image Source="Images/phone.png" Margin="20,0" x:Name="phone" Visibility="Visible">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener Tap="GestureListener_Tap_Phone"/>
</toolkit:GestureService.GestureListener>
</Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You should create a binding for the image source instead of setting it explicitly in XAML.
<ListBox x:Name="lbPharm" ItemsSource="{Binding col}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="DataTemplateStackPanel" Orientation="Horizontal">
<TextBlock FontFamily="Segoe WP Semibold" FontWeight="Bold" FontSize="30" VerticalAlignment="Top" Margin="20,10">*</TextBlock>
<StackPanel>
<TextBlock x:Name="ItemText" Text="{Binding name}" FontSize="{StaticResource PhoneFontSizeLarge}"/>
<TextBlock x:Name="ItemNumber" Text="{Binding number}" FontSize="{StaticResource PhoneFontSizeNormal}"/>
</StackPanel>
<!-- Image source is bound to a property -->
<Image Source="{Binding ImageSource}" Margin="20,0" x:Name="phone" Visibility="Visible">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener Tap="GestureListener_Tap_Phone"/>
</toolkit:GestureService.GestureListener>
</Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now, just update the property in your view model as needed, as long as the class containing the property implements INotifyPropertyChanged the new image will show up in your ListBox.
The ImageSource property may have to be a BitmapImage instead of a string. XAML must use a converter to convert your path string when it is used as a literal but I think it doesn't do this if you use a binding. Or you could use your own converter. Either way, construct a BitmapImage as follows:
new BitmapImage( new Uri( "/path/to/image.png", UriKind.Relative ) )
EDIT
Adding an example:
<DataTemplate x:Key="LongListSelectorItemTemplate">
<StackPanel VerticalAlignment="Top"
Orientation="Horizontal">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener Tap="OnTap" />
</toolkit:GestureService.GestureListener>
<Image Source="{Binding ImageSource}"
MinHeight="32"
MinWidth="32"
MaxHeight="48"
MaxWidth="48" />
<StackPanel>
<TextBlock Text="{Binding Name}"
Style="{StaticResource PhoneTextExtraLargeStyle}"
Margin="12,10,12,0" />
<TextBlock Text="{Binding Parent}"
Foreground="{StaticResource PhoneAccentBrush}"
Style="{StaticResource PhoneTextSubtleStyle}"
Margin="24,0,12,10" />
</StackPanel>
</StackPanel>
</DataTemplate>
Corresponding view model:
public class Item : INotifyPropertyChanged
{
#region Private Members
private string _name = null;
private string _imageSource = null;
private string _parent = null;
#endregion
public string Name
{
get
{
return _name;
}
set
{
if( value != _name ) {
_name = value;
NotifyPropertyChanged( "Name" );
}
}
}
public string Parent
{
get
{
return _parent;
}
set
{
if( value != _parent ) {
_parent = value;
NotifyPropertyChanged( "Parent" );
}
}
}
public string ImageSource
{
get
{
return _imageSource;
}
set
{
if( value != _imageSource ) {
_imageSource = value;
NotifyPropertyChanged( "ImageSource" );
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged( String propertyName )
{
PropertyChangedEventHandler handler = PropertyChanged;
if( null != handler ) {
handler( this, new PropertyChangedEventArgs( propertyName ) );
}
}
#endregion
}
This is code from a project I'm working on, it is similar to your case except I'm displaying the image with a LongListSelector instead of a ListBox. And it looks like I mislead you earlier about not being able to use a string directly for the image source, I'm doing exactly that and it works. Sorry about that.

Resources