So, I have a code:
<tool:LongListSelector x:Name="citiesListGropus" Background="Transparent"
ItemTemplate="{StaticResource citiesItemTemplate}"
GroupHeaderTemplate="{StaticResource groupHeaderTemplate}"
GroupItemTemplate="{StaticResource groupItemTemplate}" Height="468" Margin="0,68,0,0">
<tool:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<tool:WrapPanel/>
</ItemsPanelTemplate>
</tool:LongListSelector.GroupItemsPanel>
</tool:LongListSelector>
And have a DataTemplate:
<DataTemplate x:Key="groupHeaderTemplate" x:Name="groupHeaderTemplateName">
<Border Background="{StaticResource PhoneAccentBrush}" Width="75" Height="75" Margin="-333, 15, 0, 15" x:Name="groupHeaderName">
<TextBlock Text="{Binding Title}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
How can I change a property Visibility of Border in DataTemplate ? I want to hide DataTemplate. But I can't bind my data to a property such as TextBlock Text="{Binding Title}", because I make binding data once, then I need to change some properties after data binding.
Any Ideas?
UPDATE 1
So, my main goal is filter the list of cities. I want to filter them by name.
My algorithm:
1) I get data from WebService.
2) Load my ViewModel
if (!App.CitiesViewModel.IsDataLoaded)
{
App.CitiesViewModel.LoadData(serviceResponse.Result);
}
3) Group the cities by name. My code like this code.
This is important, especially for LongListSeletstor I have to use templates.
Ok, my data ready. Now I do not need a web service.
<!-- The template for city items -->
<DataTemplate x:Key="citiesItemTemplate">
<StackPanel Name="PlacePanel"
Orientation="Horizontal" Margin="0,0,0,17"
Tag="{Binding Id}" Visibility="{Binding IsVisibility}">
<Image Height="75" Width="75" HorizontalAlignment="Left" Margin="12,0,9,0" Name="Image" Stretch="Fill" VerticalAlignment="Top" Source="{Binding Image}"/>
<StackPanel Width="311">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
I have TextBox, when I type name of a city - unnecessary cities hide. I can use data binding and INotifyPropertyChanged, so I can hide cities.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox name = (TextBox)sender;
foreach(var place in App.CitiesViewModel.Items
.Where(city => (city.Name.Contains(name.Text)) && (city.IsShow == true)))
{
city.IsVisibility = Visibility.Visible;
}
foreach (var city in App.CitiesViewModel.Items
.Where(city => !city.Name.Contains(name.Text)))
{
city.IsVisibility = Visibility.Collapsed;
}
}
But I have some problems, I can't hide this DataTemplate when I search cities:
<DataTemplate x:Key="groupHeaderTemplate" x:Name="groupHeaderTemplateName">
<Border Background="{StaticResource PhoneAccentBrush}" Width="75" Height="75" Margin="-333, 15, 0, 15" x:Name="groupHeaderName">
<TextBlock Text="{Binding Title}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
When I type name of a cities I want hide GroupHeaderTemplate. When TextBox lost focus show GroupHeaderTemplate.
I borrowed this picture here.
Update 2
My mistake was that I did not use PropertyChangedEventHandler. After adding this to GroupCity property and implementing an interface INotifyPropertyChanged I can change property Data Template after data binding.
private IList<Group<City>> citiesCollectionGroup;
var cityByName = from city in App.ViewModel.Items
group city by Convert.ToString(City.Name[0]).ToLower()
into c orderby c.Key select new
GroupCity<CitiesViewModel>(Convert.ToString(c.Key[0]).ToLower(), c);
citiesCollectionGroup = cityByName.ToList();
this.citiesListGropus.ItemsSource = citiesCollectionGroup;
public class GroupCity<T> : IEnumerable<T>, INotifyPropertyChanged
{
public GroupCity(string name, IEnumerable<T> items)
{
this.Title = name;
this.IsVisibility = Visibility.Visible;
this.Items = new List<T>(items);
}
public override bool Equals(object obj)
{
GroupCity<T> that = obj as GroupCity<T>;
return (that != null) && (this.Title.Equals(that.Title));
}
public string Title
{
get;
set;
}
private Visibility _isVisibility;
public Visibility IsVisibility
{
get
{
return _isVisibility;
}
set
{
_isVisibility = value;
NotifyPropertyChanged("IsVisibility");
}
}
public IList<T> Items
{
get;
set;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return this.Items.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.Items.GetEnumerator();
}
#endregion
}
Xaml code:
<DataTemplate x:Key="groupHeaderTemplate" x:Name="groupHeaderTemplateName">
<Border Background="{StaticResource PhoneAccentBrush}" Width="75" Height="75" Margin="-333, 15, 0, 15" x:Name="groupHeaderName" Visibility="{Binding IsVisibility}">
<TextBlock Text="{Binding Title}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
Now we can change Visibility groupHeaderTemplate.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
foreach (GroupCity<CitiesViewModel> city in citiesCollectionGroup)
{
city.IsVisibility = Visibility.Collapsed;
}
//
}
private void SearchText_LostFocus(object sender, RoutedEventArgs e)
{
foreach (GroupCity<CitiesViewModel> city in citiesCollectionGroup)
{
city.IsVisibility = Visibility.Visible;
}
//
}
You can write your own simple DataTemplateSelector to do this. Check this out for more information.
With "How can I change a property Visibility of Border in DataTemplate ? I want to hide DataTemplate. " I understand that you want to change the visibility of an item based on a property, see example below.
(If the code below isn't quite the solution you are looking for please provide some more information about what you are trying to achieve. Re-reading your question and the comments I got on this example I doubt this is what you want to do, but I don't want to guess so I'm simply answering my interpretation of your question).
With bindings you can:
Bind the visibility property directly to a a property of type Visibility (example with listbox and Person1)
Bind the Visibility property to a boolean property, and use a converter to convert that to the Visibility type (listbox2 and Person2 + BoolToVis class).
There are more ways, but this are the two most simple to implement in my opinion.ยจ
result of code below:
View:
<phone:PhoneApplicationPage
x:Class="VisibilityWP.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" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
xmlns:VisibilityWP="clr-namespace:VisibilityWP"
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 x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.Resources>
<VisibilityWP:BoolToVis x:Key="BooleanToVisibilityConverter" />
</Grid.Resources>
<StackPanel>
<ListBox x:Name="listBox" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Width="200" Visibility="{Binding Visibility}" Background="Blue">
<TextBlock Text="{Binding Name}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox x:Name="listBox2" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Width="200" Visibility="{Binding ShowBorder, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Red">
<TextBlock Text="{Binding Name}" FontSize="40" Foreground="White" Margin="15, 15, 0, 0"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Grid>
Code behind:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
namespace VisibilityWP
{
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
DataContext = this;
listBox.ItemsSource = new List<Person1>
{
new Person1 {Name = "Iris", Visibility = Visibility.Visible},
new Person1 {Name = "Somebody", Visibility = Visibility.Collapsed},
new Person1 {Name = "Peter", Visibility = Visibility.Visible},
};
listBox2.ItemsSource = new List<Person2>
{
new Person2 {Name = "Iris", ShowBorder = true},
new Person2 {Name = "Mia", ShowBorder = true},
new Person2 {Name = "Somebody", ShowBorder = false}
};
}
}
public class Person1
{
public string Name { get; set; }
public Visibility Visibility { get; set; }
}
public class Person2
{
public string Name { get; set; }
public bool ShowBorder { get; set; }
}
public sealed class BoolToVis : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
}
Related
I have a long list selector in my application. The list should display an icon and a caption below it. It appears as a grid as seen in the image below
The icon should be downloaded from the server and displayed, the icon is downloaded from the server as an byte array which can be used to generate the Bitmap. How do i bind the Bitmap to the Image in my LongListSelectors template. My data template is as below.
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Margin="5,5,5,5" Background="{StaticResource PhoneAccentBrush}">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Image Height="70" Width="70" Margin="10,0,0,0" Source="/Assets/Images/appimg.png">
</Image>
</Grid>
<StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Center">
<TextBlock Margin="5,5,5,5" TextTrimming="WordEllipsis" TextWrapping="NoWrap" Text="{Binding appTitle}"></TextBlock>
</StackPanel>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
Currently in the template the icon path is hardcoded. Please provide some input on how to bind the bitmap to the image.
Use a Conveter
Assuming the assembly name of the phone project is: PhoneApp1
Create a converter with the following code:
using System;
namespace PhoneApp1.Converters
{
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
public class ByteToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var data = value as byte[];
if (data != null)
{
using(var stream = new MemoryStream(data))
{
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
return bitmapImage;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
use the following namespace declaration in your xaml:
xmlns:converters="clr-namespace:PhoneApp1.Converters"
XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.Resources>
<converters:ByteToImageConverter x:Key="ByteToImageConverter" />
</Grid.Resources>
<phone:LongListSelector x:Name="lstTiles">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Margin="5,5,5,5" Background="{StaticResource PhoneAccentBrush}">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Image Height="70" Width="70" Margin="10,0,0,0" Source="{Binding Image, Converter={StaticResource ByteToImageConverter}}">
</Image>
</Grid>
<StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Center">
<TextBlock Margin="5,5,5,5" TextTrimming="WordEllipsis" TextWrapping="NoWrap" Text="{Binding Title}"></TextBlock>
</StackPanel>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
Code Behind and Model
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.BindTiles();
}
private void BindTiles()
{
var sampleRandomImageBytes = Convert.FromBase64String(#"iVBORw0KGgoAAAANSUhEUgAAAGgAAABbCAYAAACf8sCiAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADeSURBVHhe7dExAQAwDMCgmVj9O21tcORAAe/PbFwF4QrCFYQrCFcQriBcQbiCcAXhCsIVhCsIVxCuIFxBuIJwBeEKwhWEKwhXEK4gXEG4gnAF4QrCFYQrCFcQriBcQbiCcAXhCsIVhCsIVxCuIFxBuIJwBeEKwhWEKwhXEK4gXEG4gnAF4QrCFYQrCFcQriBcQbiCcAXhCsIVhCsIVxCuIFxBuIJwBeEKwhWEKwhXEK4gXEG4gnAF4QrCFYQrCFcQriBcQbiCcAXhCsIVhCsIVxCuIFxBuIJwBeEKos0e0/44s5MWYKUAAAAASUVORK5CYII=");
var data = new[]
{
new AppTitle { Title = "Tile 1", Image = sampleRandomImageBytes }, new AppTitle { Title = "Tile 2", Image = sampleRandomImageBytes },
new AppTitle { Title = "Tile 3", Image = sampleRandomImageBytes }, new AppTitle { Title = "Tile 4", Image = sampleRandomImageBytes }
};
lstTiles.ItemsSource = data;
}
}
public class AppTitle
{
public string Title { get; set; }
public byte[] Image { get; set; }
}
I am developing a WP7 app that contains a LongListSelector. Within the ItemTemplate there is a ListPicker. I select a value from the ListPicker for the first item in the LongListSelector, then select a value from the ListPicker for the 2nd item. If I then scroll down the page and back to the top again, the value I selected in the ListPicker for the 1st item will be reset (SelectedIndex=0).
I have put code in the Link and Unlink events of the LongListSelector to write to the output window and I have found that when the 1st item unlinks (due to scrolling down the page), the ListPicker value is what I selected but as soon as the link event fires (due to scrolling back up the page) for the 1st item the value is reset.
Im using ObserableCollection and implement the INPC interface for my objects and the ViewModel updates when the ListPicker selection is changed.
How can I ensure that the value in the ListPickers are retaining during scrolling of the LongListSelector?
MainPage.xaml
<phone:PhoneApplicationPage
x:Class="LongListSelector.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" d:DesignWidth="480" d:DesignHeight="5000"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="occurrenceItemTemplate">
<Grid>
<StackPanel Orientation="Vertical" Margin="5,0,0,0" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Name="tbkEventDateTime" Grid.Row="0" Grid.Column="0"
Text="{Binding ItemNumber}"
Style="{StaticResource PhoneTextSmallStyle}" />
<!--<TextBox Name="txtEventDateTime" Grid.Row="1" Grid.Column="0"
Text="{Binding Result}" />-->
<toolkit:ListPicker Name="lpkResult" Margin="12,0,12,12"
Grid.Row="1" Grid.Column="0"
ItemsSource="{Binding TestItemResultList, Mode=OneTime}"
SelectedIndex="{Binding Result, Mode=TwoWay}"
CacheMode="BitmapCache">
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}" />
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
</Grid>
</StackPanel>
</Grid>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<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="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" VerticalAlignment="Stretch">
<toolkit:LongListSelector x:Name="lstOutstandingOccurrences"
Margin="0,12,0,0" Padding="0,0,0,24"
ItemTemplate="{StaticResource occurrenceItemTemplate}"
ItemsSource="{Binding TestItemCollection, Mode=TwoWay}"
IsFlatList="True" ShowListHeader="False" >
</toolkit:LongListSelector>
</Grid>
</Grid>
MainPage.xaml.cs
public partial class MainPage : PhoneApplicationPage
{
private TestItemViewModel _vm;
public TestItemViewModel ViewModel
{
get
{
if (_vm == null)
_vm = new TestItemViewModel();
return _vm;
}
private set
{
_vm = value;
}
}
// Constructor
public MainPage()
{
InitializeComponent();
this.lstOutstandingOccurrences.Link += new EventHandler<LinkUnlinkEventArgs>(lstOutstandingOccurrences_Link);
this.lstOutstandingOccurrences.Unlink += new EventHandler<LinkUnlinkEventArgs>(lstOutstandingOccurrences_Unlink);
this.DataContext = this.ViewModel;
}
void lstOutstandingOccurrences_Link(object sender, LinkUnlinkEventArgs e)
{
var item = e.ContentPresenter.Content as TestItem;
Debug.WriteLine("Link event for ItemNumber {0} = {1}", item.ItemNumber, item.Result);
}
void lstOutstandingOccurrences_Unlink(object sender, LinkUnlinkEventArgs e)
{
var item = e.ContentPresenter.Content as TestItem;
Debug.WriteLine("Unlink event for ItemNumber {0} = {1}", item.ItemNumber, item.Result);
}
}
TestItemViewModel.cs
public class TestItemViewModel : BaseINPC
{
public ObservableCollection<TestItem> TestItemCollection
{
get;
private set;
}
// Constructor
public TestItemViewModel()
{
this.TestItemCollection = new ObservableCollection<TestItem>();
CreateTestData(20);
}
public void CreateTestData(int totalItems)
{
//create test data for long list selector.
for (int i = 1; i <= totalItems; i++)
{
this.TestItemCollection.Add(new TestItem(i, 0));
}
}
}
Models
public class ListHelperListItem
{
public int Value { get; set; }
public string Text { get; set; }
}
public class TestItem : BaseINPC
{
public TestItem(int ItemNumber, int Result)
{
this.ItemNumber = ItemNumber;
this.Result = Result;
}
public int ItemNumber { get; set; }
private int _Result;
public int Result
{
get
{
return _Result;
}
set
{
//if statement is for debugging purposes only.
if (this.ItemNumber == 1)
{
_Result = value;
}
_Result = value;
RaisePropertyChanged("Result");
}
}
private List<ListHelperListItem> _TestItemResultList;
public List<ListHelperListItem> TestItemResultList
{
get
{
_TestItemResultList = new List<ListHelperListItem>();
_TestItemResultList.Add(new ListHelperListItem { Value = 0, Text = " " });
_TestItemResultList.Add(new ListHelperListItem { Value = 1, Text = "Yes" });
_TestItemResultList.Add(new ListHelperListItem { Value = 2, Text = "No" });
_TestItemResultList.Add(new ListHelperListItem { Value = 3, Text = "Ignore" });
return _TestItemResultList;
}
}
}
Thanks for your help!
I am using the _wordItems as the longlistselector's itemsource in order to dynamically delete items in longlistSelector
private ObservableCollection<Group<WordItem>> _wordItems = new ObservableCollection<Group<WordItem>>();
The Group class is defined as:
public class Group<T> : ObservableCollection<T>
{
public Group(string name, IEnumerable<T> items)
{
this.Key = name;
foreach (T item in items)
{
this.Add(item);
}
}
public override bool Equals(object obj)
{
Group<T> that = obj as Group<T>;
return (that != null) && (this.Key.Equals(that.Key));
}
public string Key
{
get;
set;
}
}
and the WordItem class is defined as:
[Table]
public class WordItem //:INotifyPropertyChanged,INotifyPropertyChanging
{
private int _wordItemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int WordItemId
{
get
{
return _wordItemId;
}
set
{
if (_wordItemId != value)
{
_wordItemId = value;
}
}
}
private string _word;
[Column(CanBeNull=false)]
public string Word
{
get
{
return _word;
}
set
{
if (_word != value)
{
_word = value;
}
}
}
private string _wordExplains;
[Column]
public string WordExplains
{
get
{
return _wordExplains;
}
set
{
if (_wordExplains != value)
{
_wordExplains = value;
}
}
}
}
when I use the code _wordItems[1].RemoveAt(1);, the _wordItems has been modified, and the longlistselector in the screen has also deleted certain item. But the problem is that when I call _wordItems[1].RemoveAt(1);, the longlistselector just deleted the _wordItems[1][0] item. When I call _wordItems[1].RemoveAt(0);, it just deleted the header of the second group and combined the items in _worditems[1] with the _wordItem[0].
The definition of longlistselector:
<toolkit:LongListSelector x:Name="WordsGroup" Background="Transparent"
Margin="12,0,12,73" ItemTemplate="{StaticResource WordItemTemplate}"
GroupHeaderTemplate="{StaticResource YoudaoGroupHeaderTemplate}"
GroupItemTemplate="{StaticResource YoudaoGroupItemTemplate}"
SelectionChanged="WordsGroup_SelectionChanged"
>
<toolkit:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>
The datatemplate is as:
<DataTemplate x:Key="WordItemTemplate">
<Border BorderBrush="Gray" BorderThickness="0,0,0,0" Margin="0,3,0,5">
<StackPanel >
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu Opened="ContextMenu_Opened" >
<toolkit:MenuItem Header="delete this word" Click="DelectWord_Click"/>
<toolkit:MenuItem Header="share this word" Click="SMSShare_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlock Text="{Binding WordItemId}" Style="{StaticResource PhoneTextNormalStyle}" Visibility="Collapsed"/>
<TextBlock Text="{Binding Word}" Style="{StaticResource PhoneTextNormalStyle}" FontSize="25" Foreground="Black" FontWeight="Bold"/>
<TextBlock Text="{Binding WordExplains}" Style="{StaticResource PhoneTextNormalStyle}" Foreground="Black" TextWrapping="Wrap"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="YoudaoGroupHeaderTemplate">
<Border Background="#1BA1E2" Margin="0">
<TextBlock Text="{Binding Key}" FontSize="30" Margin="12,0,0,0" Foreground="Black" />
</Border>
</DataTemplate>
<DataTemplate x:Key="YoudaoGroupItemTemplate" >
<Border Background="#1BA1E2" Width="99" Height="99" Margin="6">
<TextBlock Text="{Binding Key}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="40" Foreground="{StaticResource PhoneForegroundBrush}"/>
</Border>
</DataTemplate>
Thx in advance.
ps. I am using the linq as
var wordBy4sLetter = from word in wordList
group word by word.Word.ToCharArray()[0].ToString() into s
orderby s.Key
select new Group<WordItem>(s.Key, s);
this._wordItems = wordBy4sLetter.ToObservableCollection();
this.WordsGroup.ItemsSource = this._wordItems;
I think you need another ObservableCollection. Take a look at the accepted answer for this question. Group Listbox for Windows Phone 7?
I have modified the code there and created new Add/Remove methods that will create a group if not there for an add, and remove the group if it's empty on a remove.
I am trying to implement the LongListSelector in a new WP7 application. The LongListSelector exists in a UserControl bound to an MVVMLight view model. I get the following error when I try to load the UserControl:
System.ArgumentException was unhandled
Message=The parameter is incorrect.
StackTrace:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, Double d)
at System.Windows.DependencyObject.SetValue(DependencyProperty property, Double d)
at System.Windows.FrameworkElement.set_Width(Double value)
at Microsoft.Phone.Controls.LongListSelector.GetAndAddElementFor(ItemTuple tuple)
at Microsoft.Phone.Controls.LongListSelector.Balance()
at Microsoft.Phone.Controls.LongListSelector.EnsureData()
at Microsoft.Phone.Controls.LongListSelector.LongListSelector_Loaded(Object sender, RoutedEventArgs e)
at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
I have been able to narrow down the problem to the Items in my binding source, however I cannot see what the problem is.
Here is the XAML from my UserControl:
<UserControl x:Class="BTT.PinPointTime.WinPhone.Views.TaskSelectionControl"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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}"
d:DesignHeight="480"
d:DesignWidth="480"
DataContext="{Binding Source={StaticResource Locator}, Path=TaskSelection}">
<UserControl.Resources>
<DataTemplate x:Key="itemTemplate">
<StackPanel Grid.Column="1"
VerticalAlignment="Top">
<TextBlock Text="{Binding Name}"
FontSize="26"
Margin="12,-12,12,6" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="groupHeaderTemplate">
<Border Background="YellowGreen"
Margin="6">
<TextBlock Text="{Binding Title}" />
</Border>
</DataTemplate>
<DataTemplate x:Key="groupItemTemplate">
<Border Background="Pink"
Margin="6">
<TextBlock Text="{Binding Title}" />
</Border>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<toolkit:LongListSelector Grid.Row="1"
Background="Red"
ItemsSource="{Binding GroupedTasks}"
GroupItemTemplate="{StaticResource groupItemTemplate}"
ItemTemplate="{StaticResource itemTemplate}"
GroupHeaderTemplate="{StaticResource groupHeaderTemplate}">
<toolkit:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel />
</ItemsPanelTemplate>
</toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>
</Grid>
</Grid>
And here is the code that I am using to populate the GroupedTasks property in my view model (it is declared as ObservableCollection> GroupedTasks):
private void LoadData()
{
if (App.Database.Query<Task, Guid>().Count() > 0)
{
GroupedTasks.Clear();
var tasks = (from t in App.Database.Query<Task, Guid>().ToList() select t.LazyValue.Value);
var groupedTasks = from t in tasks
group t by t.FullParentString into t1
orderby t1.Key
//select new Group<Task>(t1.Key, t1);
select new Group<Task>(t1.Key);
foreach (Group<Task> o in groupedTasks)
{
GroupedTasks.Add(o);
}
foreach (Group<Task> g in GroupedTasks)
{
var currentTasks = (from t in tasks where t.FullParentString == g.Title select t);
foreach (Task t in currentTasks)
{
g.Add(t);
}
}
}
_isDataLoaded = true;
}
and finally here is the declaration of my Group class:
public class Group<T> : ObservableCollection<T>
{
public string Title
{
get;
set;
}
public bool HasItems
{
get
{
return Count != 0;
}
private set
{
}
}
public Group(string name)
{
this.Title = name;
}
}
I did originally implement this as a simple IEnumerable as per the turorial on Windows Phone Geek. However that gave me exactly the same error.
I do not get any binding errors, however there is nothing that I can see that will enable me to track down the source of the problem.
The answer is found here: http://silverlight.codeplex.com/workitem/7707. Basically add a width and height to the LongListSelector.
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.