EDIT:
Program: I have a list of car model names and beside them numbers from 1 to 4, the user gets to input the number in the Textbox of the car he/she wants to save. The number correlates to the name of the car and saves it in the stringbuilder append.
Problem: How do I save the words that are put in the Textbox in a Stringbuilder Append? Also can I create another textbox and save other words threw the same Stringbuilder?
public partial class MainWindow : Window
{
ObservableCollection<string> Items = new ObservableCollection<string>();
StringBuilder sb = new StringBuilder();
public MainWindow()
{
InitializeComponent();
Items.Add("1.Honda");
Items.Add("2.Toyota");
Items.Add("3.Fiat");
Items.Add("4.Ferrari");
}
private void SaveFile_Click(object sender, RoutedEventArgs e)
{
if (txtValue.Text == "1"){txtValue.Text = "Honda";}
if (txtValue.Text == "2") { txtValue.Text = "Toyota"; }
if (txtValue.Text == "3") { txtValue.Text = "Fiat"; }
if (txtValue.Text == "4") { txtValue.Text = "Ferrari"; }
foreach (string txtValue in Items) //Just playing around trying to figure out how to Append
{
sb.Append(Items).AppendLine();
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
File.WriteAllText(saveFileDialog.FileName, txtValue.Text);
}
}
}
XAML
<Window.Resources>
<x:Array x:Key="Items" Type="{x:Type sys:String}"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:String>1.Honda</sys:String>
<sys:String>2.Toyota</sys:String>
<sys:String>3.Fiat</sys:String>
<sys:String>4.Ferrari</sys:String>
</x:Array>
</Window.Resources>
<Grid>
<StackPanel Margin="10">
<TextBox x:Name="txtValue" />
<ListBox Height=" 100" ItemsSource="{StaticResource Items}" >
</ListBox>
<Button Name="SaveFile" Click="SaveFile_Click" >OK</Button>
</StackPanel>
</Grid>
</Window>
Related
My Situation:
I'm trying to affect a label from one TabItem of a TabControl by clicking a Button on another TabItem of the same TabControl.
I'm currently having a hard time figuring out why the property of my TextBox textBoxTyp won't change its value even after updating the property. The binding is correct an a button right next to the TextBox (on the same TabItem) that's bound exactly like the other Button from the other `Tabitem, works perfectly fine. I'm using the MVVM pattern and databinding.
Here the code of the TabControl itself
<TabControl Name="TabSpaces"
SelectedIndex="{Binding TabIndex, Mode=TwoWay, Source={StaticResource vm_Für_Typenschild}}"
Background="White" Margin="0,0,0,-4">
<TabItem DataContext="{Binding TypneschildVM, Source={StaticResource vm_Für_Typenschild}}"
FontSize="15" Foreground="White" FontWeight="Bold" Background="#401746"
Header="Datei" Margin="0,0,-60,0">
<view:DateiV/>
</TabItem>
<TabItem MouseLeftButtonDown="SelectedTypenschild" Loaded="Typenschild_Loaded"
FontSize="15" Height="50" Foreground="White" FontWeight="Bold"
Background="#401746" Header="Typenschild" BorderBrush="#FFACACAC"
Margin="56,0,-128,0">
<view:TypenschildVM Width="Auto" Height="Auto" HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch" Margin="1,0"/>
</TabItem>
</TabControl>
Here the code from the view of the TabItem with the button that should affect the TextBox
<Button Command="{Binding ReadXmlAndInsertIntoDialogsIntoTypenSchild_Command, Source={StaticResource vm_Für_Typenschild}}"
FontSize="25" x:Name="button_Datei_entfernen" Foreground="White"
Content="Datei entfernen" HorizontalAlignment="Center" Margin="476,468,476,215"
VerticalAlignment="Center" Width="326" Height="70">
</Button>
Here the code from the functions that should change the property ( ReadXmlAndInsertIntoDialogsIntoTypenSchild & CompareXmlWithJsonAndInsertIntoDialog )
namespace WPF_App_RFID_SpinOff.ViewModel
{
public class TypneschildVM : INotifyPropertyChanged, ICommand
{
private string CompareXmlWithJsonAndInsertIntoDialog(string XmlFileStringToCheck, string IdFromJsonFile)
{
string ValueTopass = "";
string line = "";
StringReader StringReaderOfXmlFile = new StringReader(XmlFileStringToCheck);
while ((line = StringReaderOfXmlFile.ReadLine()) != null)
{
if (line.Contains(IdFromJsonFile) == true)
{
int IndexRightNow = line.IndexOf('V');
int IndexWhereValueStart = line.IndexOf('V');
int CounterToGetValue = 0;
for (CounterToGetValue = IndexWhereValueStart + 1; CounterToGetValue < line.Length; CounterToGetValue++)
{
if (line[CounterToGetValue] != '"' && line[CounterToGetValue] != '=' && line[CounterToGetValue] != '/' && line[CounterToGetValue] != '>')
{
ValueTopass += line[CounterToGetValue];
}
}
}
}
return ValueTopass;
// Console.WriteLine(TypenschildM_ToUse.Hardwareversion);
}
public void ReadXmlAndInsertIntoDialogsIntoTypenSchild(object parameter)
{
int OpenBracketCount = 0;
string IdFromJsonFile = "";
string StringOfJsonFile = StaticFunc.ProvideJsonFile();
string StringOfXmlFile = StaticFunc.ProvideXMLFile();
string StringOfInformationforTypenschildFromXml = GetPartOfXmlFileForTypenSchild(StringOfXmlFile);
string StringOfInformationforTypenschildFromJson = GetPartOfJsonFileForTypenSchild(StringOfJsonFile);
string BlockOfDataforCertainValue = " ";
Console.WriteLine("test");
foreach (char character in StringOfJsonFile)
{
if (character == '{')
{
OpenBracketCount++;
}
if (OpenBracketCount >= 1)
{
BlockOfDataforCertainValue += character;
if (character == '}')
{
Console.WriteLine(BlockOfDataforCertainValue);
IdFromJsonFile = lookOutForID(BlockOfDataforCertainValue);
PropTest = CompareXmlWithJsonAndInsertIntoDialog(StringOfXmlFile, IdFromJsonFile);
OnPropertyChanged("PropTest");
}
}
}
}
#region ICommandSchnittstelle
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
public void Execute(object parameter)
{
throw new NotImplementedException();
}
#endregion
public TypneschildVM()
{
TypenschildM TypenschildM_ToUse = TypenschildM.Instance;
LeseXMLAus = new RelayCommand(ReadXMLFileForTypenschildVM, StaticFunc.enableExecute);
ReadXmlAndInsertIntoDialogsIntoTypenSchild_Command = new RelayCommand(ReadXmlAndInsertIntoDialogsIntoTypenSchild, StaticFunc.enableExecute);
startButtoon_Command = new RelayCommand(ReadXmlAndInsertIntoDialogsIntoTypenSchild, StaticFunc.enableExecute);
}
}
}
Heres The Binding of my Textbox
<TextBox IsReadOnly="True"
Text="{Binding PropTest, Source={StaticResource vm_Für_Typenschild}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
x:Name="textBoxTyp" Height="22" Margin="243,93,133,0" TextWrapping="Wrap"
VerticalAlignment="Top" Background="#FFF3F3F3" Grid.Column="2"/>
I am creating UWP app, and I maked external arrow "marker" of selected item in listview...
Like this:
I have managed to achieve this with next code:
var current = lvMain.Items.FirstOrDefault(a => (a as MyModel).Selected) as MyModel;
ListViewItem selected = lvMain.ContainerFromItem(current) as ListViewItem;
GeneralTransform generalTransform1 = gvEpg.TransformToVisual(selected);
Point currentPoint = generalTransform1.TransformPoint(new Point());
In Scroll change event I am calling this and set the arrow position by the Point of my item. And this is working.
But, I want to simplified this. Is there any kind of binding or something like that, that would make arrow always follow the item?
Here's the sample.
XAML MainPage:
<Page.Resources>
<DataTemplate x:Key="DataTemplate">
<Canvas Height="80" Width="200">
<TextBlock Text="{Binding}"/>
</Canvas>
</DataTemplate>
</Page.Resources>
<StackPanel Orientation="Horizontal">
<ListView x:Name="ListView" Width="400"
SelectionChanged="ListView_OnSelectionChanged"
ItemTemplate="{StaticResource DataTemplate}"/>
<Canvas x:Name="ParentCanvas">
<Image x:Name="Arrow"
Stretch="UniformToFill" Width="200" Height="80"
Source="Assets/Red_Left_Arrow.png"/>
</Canvas>
</StackPanel>
Code behind:
private readonly List<string> _names = new List<string>();
private Visual _rectangleVisual;
private Visual _parentVisual;
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 32; i++)
{
_names.Add("item " + i);
}
ListView.ItemsSource = _names;
_parentVisual = ElementCompositionPreview.GetElementVisual(ParentCanvas);
_rectangleVisual = ElementCompositionPreview.GetElementVisual(Arrow);
var border = VisualTreeHelper.GetChild(ListView, 0) as Border;
var scrollViewer = border.Child as ScrollViewer;
var scrollerProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scrollViewer);
var offsetExpressionAnimation = _rectangleVisual.Compositor.CreateExpressionAnimation("Scroller.Translation.Y");
offsetExpressionAnimation.SetReferenceParameter("Scroller", scrollerProperties);
_rectangleVisual.StartAnimation("Offset.Y", offsetExpressionAnimation);
}
private void ListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listViewItem = ListView.ContainerFromItem(ListView.SelectedItem) as ListViewItem;
var listItemVisual = ElementCompositionPreview.GetElementVisual(listViewItem);
_parentVisual.Offset = new Vector3(_parentVisual.Offset.X, listItemVisual.Offset.Y, 0);
}
Looks like what you asked for:
I don't want to random number, I want to random all the items in the listbox in C# XAML Windows Store App??
Anyone have code for that or have any idea how to do that?
I have this code of listbox
<ListBox Name="Playlist" Background="White" DoubleTapped="Playlist_DoubleTapped" KeyUp="Playlist_KeyUp"
Foreground="Black" SelectionMode="Single" SelectionChanged="Playlist_SelectionChanged"
ScrollViewer.VerticalScrollMode="Enabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Grid.Column="0" Margin="28,82,1067,32">
#Baldrick this is how i am adding songs/videos to the playlist listbox
public async void OpenFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.List;
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
filePicker.CommitButtonText = "Play";
foreach (string fileExtension in supportedAudioFormats)
{
filePicker.FileTypeFilter.Add(fileExtension);
}
foreach (string fileExtension in supportedVideoFormats)
{
filePicker.FileTypeFilter.Add(fileExtension);
}
IReadOnlyList<StorageFile> selectedFiles = await filePicker.PickMultipleFilesAsync();
if (selectedFiles.Count > 0)
{
foreach (StorageFile file in selectedFiles)
{
Playlist.Items.Add(file);
}
systemMediaControls.IsEnabled = true;
mediaSource.AutoPlay = true;
await SetNewMediaItem(0); // Start with first file in the list of picked files.
StorageFile files = Playlist.SelectedItem as StorageFile;
Thumbnail(files);
}
}
Here is an example.
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Name="Playlist" ItemsSource="{Binding Path=PlaylistItems}"/>
<Button Grid.Row="1" Name="Shuffle" Content="Shuffle" Click="Shuffle_Click"/>
</Grid>
Note that there is PlaylistItems binded to ListBox. It would be the best to manipulate the collection of items, which is binded to ListBox, instead of manipulating ListBox itself.
C# code:
First you should define that PlaylistItems collection.
public ObservableCollection<string> PlaylistItems
{
get;
set;
}
And to make it possible to bind it to the ListBox, it is necessary to set the DataContext of your control (window or whatever).
public MainWindow()
{
InitializeComponent();
this.DataContext = this; // <--
}
Now let's initialize PlaylistItems collection and add few items.
public void InitializeItems(int count)
{
var items = new List<string>(count);
for (int i = 0; i < count; i++)
items.Add("Item " + i);
PlaylistItems = new ObservableCollection<string>(items);
}
You can call this method in the constructor.
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
InitializePlaylist(10); // <--
}
And finally shuffle functionality.
public IEnumerable<string> ShuffleItems(IEnumerable<string> items)
{
var rnd = new Random();
return items.OrderBy(item => rnd.Next()).ToList();
}
Use it in your button handler to repopulate PlaylistItems with randomized items.
private void Shuffle_Click(object sender, RoutedEventArgs e)
{
var shuffledItems = ShuffleItems(PlaylistItems);
PlaylistItems.Clear();
foreach (var item in shuffledItems)
PlaylistItems.Add(item);
}
I have silverlight web app.I am showing log information in child windows.child window contain a textbox control.I have set ScrollViewer.VerticalScrollBarVisibility="Auto" but vertical scroll bar is not showing up.please help me on this.
XAML
<controls:ChildWindow x:Class="LogPopUpWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
Width="600" Height="400"
Title="" HasCloseButton="False">
<Grid x:Name="LayoutRoot" Margin="2">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox x:Name="LogEvents" IsReadOnly="True" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Visible"></TextBox>
<Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />
</Grid>
C#
public void RefreshLogs(string message = "")
{
StringBuilder text = new StringBuilder();
if (string.IsNullOrEmpty(message))
{
if (Logger.GetLogs() != null)
{
Logger.GetLogs().ForEach(b =>
{
text.AppendFormat("{2}{0}: {1}{2}", b.UserTargetOperation, b.UserEventDate.ToString(), Environment.NewLine);
foreach (KeyValuePair<string, string> pair in b.Parameters)
{
text.AppendFormat(" {0} : {1}{2}", pair.Key, pair.Value, Environment.NewLine);
}
});
}
LogEvents.Text = text.ToString();
}
else
{
LogEvents.Text = message;
LogEvents.TextWrapping = TextWrapping.Wrap;
}
}
Button Handler Coder
private void ShowLogLink_Click(object sender, System.Windows.RoutedEventArgs e)
{
///Logger.GetLogs();
///
LogPopUpWindow win = new LogPopUpWindow();
win.RefreshLogs();
win.Show();
}
I would put this just in a comment but I don't have enough rep. I tried to reproduce the error you are describing of that the Vertical Scroll bar is not displaying, but when I fill the textbox with more text than it's height holds, the scroll bar shows.
Is there any other portions influencing your problem that you did not list?
Issue is resolved.I added vertical scroll properties in the code and it is working.
public void RefreshLogs(string message = "")
{
StringBuilder text = new StringBuilder();
if (string.IsNullOrEmpty(message))
{
if (Logger.GetLogs() != null)
{
Logger.GetLogs().ForEach(b =>
{
text.AppendFormat("{2}{0}: {1}{2}", b.UserTargetOperation, b.UserEventDate.ToString(), Environment.NewLine);
foreach (KeyValuePair<string, string> pair in b.Parameters)
{
text.AppendFormat(" {0} : {1}{2}", pair.Key, pair.Value, Environment.NewLine);
}
});
}
LogEvents.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; // added
LogEvents.Text = text.ToString();
}
else
{
**LogEvents.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;** // added
LogEvents.Text = message;
LogEvents.TextWrapping = TextWrapping.Wrap;
}
}
}
I am trying to make Alphabetically searching of records via accessing rest services in windows phone 7.
Design page code..
<controls:PivotItem Header="buddies">
<toolkit:LongListSelector x:Name="BookList" Background="Transparent" IsFlatList="true"
GroupViewOpened="LongListSelector_GroupViewOpened"
GroupViewClosing="LongListSelector_GroupViewClosing">
<toolkit:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</toolkit:LongListSelector.GroupItemsPanel>
<toolkit:LongListSelector.GroupItemTemplate>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource GroupBackground}}"
Width="99" Height="99" Margin="6" IsHitTestVisible="{Binding HasItems}">
<TextBlock Text="{Binding Title}"
FontFamily="{StaticResource PhoneFontFamilySemiBold}"
FontSize="48"
Margin="8,0,0,0"
Foreground="{Binding Converter={StaticResource GroupForeground}}"
VerticalAlignment="Bottom"/>
<Border.Projection>
<PlaneProjection RotationX="-60"/>
</Border.Projection>
</Border>
</DataTemplate>
</toolkit:LongListSelector.GroupItemTemplate>
<toolkit:LongListSelector.GroupHeaderTemplate>
<DataTemplate>
<Border Background="Transparent" Margin="12,8,0,8">
<Border Background="{StaticResource PhoneAccentBrush}"
Padding="8,0,0,0" Width="62" Height="62"
HorizontalAlignment="Left">
<TextBlock Text="{Binding Title}"
Foreground="#FFFFFF"
FontSize="48"
FontFamily="{StaticResource PhoneFontFamilySemiLight}"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"/>
</Border>
</Border>
</DataTemplate>
</toolkit:LongListSelector.GroupHeaderTemplate>
<toolkit:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Margin="12,8,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Width="110" Height="150" Source="{Binding ImageUrl}" VerticalAlignment="Top"/>
<StackPanel Grid.Column="1" VerticalAlignment="Top">
<TextBlock Text="{Binding AutherName}" Style="{StaticResource PhoneTextLargeStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" Margin="12,-12,12,6"/>
<TextBlock Text="{Binding Email}" Style="{StaticResource PhoneTextNormalStyle}" TextWrapping="Wrap" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Title:" Style="{StaticResource PhoneTextSmallStyle}"/>
<TextBlock Text="{Binding Title}" Style="{StaticResource PhoneTextSmallStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Price:" Style="{StaticResource PhoneTextSmallStyle}"/>
<TextBlock Text="{Binding Price}" Style="{StaticResource PhoneTextSmallStyle}" FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</toolkit:LongListSelector.ItemTemplate>
</toolkit:LongListSelector>
</controls:PivotItem>
</controls:Pivot>
</Grid>
Here is my MainPage.xaml.cs page code
private LongListSelector currentSelector;
List<Person> objperson = null;
// Constructor
public MainPage()
{
InitializeComponent();
string Categoryid = "2";
WebClient proxy = new WebClient();
proxy.DownloadStringAsync(new Uri("http://localhost:3160/Service1.svc/GetListItemDetail/" + Categoryid));
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
}
void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument doc = XDocument.Load(new StringReader(e.Result));
var CatList = (from item in doc.Descendants("ItemDetail")
select new Person
{
GenreName = item.Element("GenreName").Value.ToString(),
ItemID = Convert.ToInt32(item.Element("ItemID").Value),
CatID = Convert.ToInt32(item.Element("CatID").Value),
GenreID = Convert.ToInt32(item.Element("GenreID").Value),
AutherName = item.Element("AutherName").Value.ToString(),
Title = item.Element("Title").Value.ToString(),
Email = item.Element("Email").Value.ToString(),
Price = item.Element("Price").Value.ToString(),
Description = item.Element("Description").Value.ToString(),
ImageUrl = item.Element("ImageUrl").Value.ToString()
}).ToList();
objperson = new List<Person>();
objperson = CatList;
BookList.ItemsSource = CatList;
}
}
public List<Person> GetPersonListInfo()
{
List<Person> objp = new List<Person>();
objp = objperson;
return objp;
}
private void LongListSelector_GroupViewOpened(object sender, GroupViewOpenedEventArgs e)
{
//Hold a reference to the active long list selector.
currentSelector = sender as LongListSelector;
//Construct and begin a swivel animation to pop in the group view.
IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
Storyboard _swivelShow = new Storyboard();
ItemsControl groupItems = e.ItemsControl;
foreach (var item in groupItems.Items)
{
UIElement container = groupItems.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
if (container != null)
{
Border content = VisualTreeHelper.GetChild(container, 0) as Border;
if (content != null)
{
DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
showKeyFrame1.Value = -60;
showKeyFrame1.EasingFunction = quadraticEase;
EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(85);
showKeyFrame2.Value = 0;
showKeyFrame2.EasingFunction = quadraticEase;
showAnimation.KeyFrames.Add(showKeyFrame1);
showAnimation.KeyFrames.Add(showKeyFrame2);
Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
Storyboard.SetTarget(showAnimation, content.Projection);
_swivelShow.Children.Add(showAnimation);
}
}
}
_swivelShow.Begin();
}
private void LongListSelector_GroupViewClosing(object sender, GroupViewClosingEventArgs e)
{
//Cancelling automatic closing and scrolling to do it manually.
e.Cancel = true;
if (e.SelectedGroup != null)
{
currentSelector.ScrollToGroup(e.SelectedGroup);
}
//Dispatch the swivel animation for performance on the UI thread.
Dispatcher.BeginInvoke(() =>
{
//Construct and begin a swivel animation to pop out the group view.
IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
Storyboard _swivelHide = new Storyboard();
ItemsControl groupItems = e.ItemsControl;
foreach (var item in groupItems.Items)
{
UIElement container = groupItems.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
if (container != null)
{
Border content = VisualTreeHelper.GetChild(container, 0) as Border;
if (content != null)
{
DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
showKeyFrame1.Value = 0;
showKeyFrame1.EasingFunction = quadraticEase;
EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(125);
showKeyFrame2.Value = 90;
showKeyFrame2.EasingFunction = quadraticEase;
showAnimation.KeyFrames.Add(showKeyFrame1);
showAnimation.KeyFrames.Add(showKeyFrame2);
Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
Storyboard.SetTarget(showAnimation, content.Projection);
_swivelHide.Children.Add(showAnimation);
}
}
}
_swivelHide.Completed += _swivelHide_Completed;
_swivelHide.Begin();
});
}
private void _swivelHide_Completed(object sender, EventArgs e)
{
//Close group view.
if (currentSelector != null)
{
currentSelector.CloseGroupView();
currentSelector = null;
}
}
I am new to windows phone 7 application development, no idea about grouping of alphabets in Longlistselector. Please help me in that. Thanks in advance.
There is code I used once for grouping. As you can see, it's similar to Claus's:
public class YourList : ObservableCollection<ItemsInGroup>
{
private static readonly string Groups = "#abcdefghijklmnopqrstuvwxyz";
Dictionary<string, ItemsInGroup> groups = new Dictionary<string, ItemsInGroup>();
public YourList()
{
foreach (char c in Groups)
{
ItemsInGroup group = new ItemsInGroup(c.ToString());
this.Add(group);
groups[c.ToString()] = group;
}
}
public void AddItem(Item item)
{
string GroupKey = Item.GetSomeFieldKey(item);// a, b, etc.
for (int i = 0; i < groups[GroupKey].Count; i++)
{
if (Item.CompareBySomeField(item, groups[GroupKey][i]) < 0)
{
groups[Item.GetSomeFilesKey(item)].Insert(i, item);
return;
}
}
groups[GroupKey].Add(item);
}
}
.
public class ItemsInGroup : ObservableCollection<Item>, INotifyPropertyChanged
{
public ItemsInGroup(string category)
{
Key = category;
}
public string Key { get; set; }
public bool HasItems { get { return Count > 0; } }
//INotifyPropertyChanged implementation
}
Item must implement:
public static string GetSomeFieldKey(Item item)
and
public static int CompareBySomeFields(object obj1, object obj2)
Usage:
YourList list = new YourList();
foreach (var item in resultListFromService)
{
list.AddItem(item); // fill list with items
}
myList.ItemsSource = list; // bind to UI
Hope this helps better understand how it works
A super easy way to do it, is to use a specialized collection for the LongListSelector. I just so happen to have written one
Basically you would change your code to the following:
BookList.ItemsSource = new LongListCollection<Person, char>(CatList, x => x.Title[0]));
And you would get the alphabetic grouping on the first character of the Title property.
The only detail you need to be aware of, is that your Person class would need to implement IComparable<Person> to be ordered by the Title property (because you do want sorting, right?)
Simply done as:
public int Compare(Person other)
{
if (other == null)
return 1;
return this.Title.CompareTo(other.Title);
}