Windows Phone 7 - Images & Themes in a databound listbox - windows-phone-7

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.

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"

How to change pivot header into page number?

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();
}
}

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>

ListBox in wp7 doesn't work for me

I'm trying to present a listview in wp7 and for some reason it doesn't seem to work
my xaml
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel2" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="list">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<Image Source="{Binding ImageUri}" Stretch="None"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
my c# code
public class list
{
public string title { get; set; }
public string imageSource { get; set; }
}
and
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
List<list> dataSources = new List<list>();
dataSources.Add(new list() { title = "Shacharit", imageSource = "Images/shacharit.png" });
dataSources.Add(new list() { title = "Mincha", imageSource = "Images/mincha.png" });
dataSources.Add(new list() { title = "Arvit", imageSource = "Images/arvit.png" });
dataSources.Add(new list() { title = "Birkat HaMazon", imageSource = "Images/shacharit.png" });
list.ItemsSource = dataSources;
}
Thanks in advance
Try the below, change the bindings of image and text block to bind to the strings you have declared at present you are trying to bind to ImageURI and Text and they don't exist in any of your code.
<!--ContentPanel - place additional content here-->
<StackPanel x:Name="ContentPanel2" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="list" Da>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<Image Source="{Binding imageSource }" Stretch="None"/>
<TextBlock Text="{Binding title}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
To Clarify Jon D's answer, you are creating data objects with attributes of "imagePath" and "title" in your code behind
new list() { title = "Shacharit", imageSource = "Images/shacharit.png" };
but trying to bing to properties called "ImageUri" and "Text".
In your output window in VS you should see these binding errors show up.
The following 2 lines (where you are doinng the binding in the XAML) should fix things up for you...
<Image Source="{Binding imageSource }" Stretch="None"/>
<TextBlock Text="{Binding title}"/>

WP7 image binding

I have a Windows phone 7 application which contains a listbox. I want, for each item in the listbox to have a particular image.
<ListBox Height="606" HorizontalAlignment="Left" ScrollViewer.VerticalScrollBarVisibility="Visible"
Margin="20,20,0,0"
Name="listBox1" VerticalAlignment="Top" Width="414" ItemsSource="{Binding SubList, Mode=OneWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Height="50" Width="50"
VerticalAlignment="Top" Margin="0,10,8,0" Source="{Binding Image, Mode = OneWay}"/>
<StackPanel Orientation="Vertical">
<HyperlinkButton Content="{Binding Cathegory, Mode=OneWay}" NavigateUri="" HorizontalAlignment="Right">
</HyperlinkButton>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And the property binded to the Source property of the Image control is an Uri.
My problem is that the image is not shown in the listbox.
I have tried using a string instead of the Uri but I get the same issue.
I kindly appreciate any help :).
This should work:
public class Item
{
public int Number { get; set; }
public Uri ImageUri { get; set; }
public Item(int number, Uri imageUri)
{
Number = number;
ImageUri = imageUri;
}
}
And the datatemplate:
<ListBox x:Name="Items">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"></TextBlock>
<Image Source="{Binding ImageUri}"></Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Check out this other SO answer, I believe it contains the answer to your question:
Image UriSource and Data Binding
But the basics of it is that you need to convert your URI/string to a BitmapImage (either via viewmodel property, or converter)

Resources