I'm trying to find an efficient way to set a limit to each of my group in a linq request in C# (7 items by group for example). I don't want to create another group with the extra of one group I just want to pass to another category.
For the moment I'm doing this to fill my groupedList :
public IEnumerable<object> ListByCategory
{
get
{
var query = from item in listArticles.listArticles
orderby item.categorie
group item by item.categorie into g
select g;
return query;
}
}
I tried to go through this groupedList afterward and remove all the extra element in each category but it is not elegant at all.
Thank you in advance
Here is the Xaml part :
<local:MyGridView x:Name="PicturesGridView" SelectionMode="None"
ItemsSource="{Binding Source={StaticResource cvs1}}" IsItemClickEnabled="True" ItemTemplate="{StaticResource CustomTileItem}" ItemClick="ItemView_ItemClick" >
<local:MyGridView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</local:MyGridView.ItemsPanel>
<local:MyGridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Button Click="Button_Click_1" Content="{Binding Key}" Foreground="Black" Background="White" FontSize="30" Margin="0,0,0,-10" ></Button>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid ItemWidth="75" ItemHeight="150" Orientation="Vertical" Margin="0,0,80,0" MaximumRowsOrColumns="3"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</local:MyGridView.GroupStyle>
</local:MyGridView>
Here are the ressources :
<DataTemplate x:Key="CustomTileItem">
<Grid >
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding imageUrl}" Stretch="UniformToFill"/>
</Border>
<StackPanel VerticalAlignment="Bottom" >
<TextBlock Text="{Binding title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="30" Margin="15,0,15,0"/>
<TextBlock Text="{Binding chapo}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
</StackPanel>
</Grid>
</DataTemplate>
<CollectionViewSource x:Name="cvs1"
IsSourceGrouped="True" />
and I'm doing the binding like this :
IEnumerable<object> myObject = App.api.ListByCategory;
this.cvs1.Source = App.api.ListByCategory;
If I understand your request correctly, you can just use Take:
return from item in listArticles.listArticles
orderby item.categorie
group item by item.categorie into g
select g.Take(7);
(Obviously that can be a variable...)
Note that this will lose the fact that it's a grouping, so you'll no longer be able to take the key from each group. If that's a problem, you can select to a new data structure easily enough. For example:
return from item in listArticles.listArticles
orderby item.categorie
group item by item.categorie into g
select new { g.Key, Values = g.Take(7) };
Related
I know there should be a simple solution to this question but I just cant seem to figure it out here is what my code looks like:
<ListBox HorizontalAlignment="Left"
x:Name="locationsNB"
VerticalAlignment="Top"
Height="563"
Width="455"
SelectionChanged="locationsNB_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Margin="18,0,0,0"
x:Name="placeDetails">
<Image Source="{Binding icon}"
Height="40"
Width="40"
VerticalAlignment="Top"
Margin="0,10,8,0" />
<StackPanel Width="350">
<TextBlock Text="{Binding name}"
FontSize="35"
Foreground="#399B81"
TextWrapping="Wrap" />
<TextBlock Text="{Binding vicinity}"
FontSize="20"
Foreground="#888888"
TextWrapping="Wrap" />
<TextBlock x:Name="reference"
Text="{Binding reference}"
Visibility="Collapsed" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I want to get the stackpanel->reference text (Text="{Binding reference}") of the selected item I dont know what my C# should look like but any help will be greatly appreciated.
If the ItemsSource of your ListBox is bound to a collection of items then you can use the SelectedItem property of the ListBox
private void locationsNB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listbox = (ListBox)sender;
var myObject = listbox.SelectedItem as MyCustomObject;
if (myObject == null) return;
// perform your custom logic with this item
}
I'm making a nested listed box , basically because I need to bind multiple classes in a single list box , which I'm not able to do and hence the nested listed box.
Here's what I do in the XAML page :
<ListBox Name="abcd" Margin="10,0,30,0" ItemsSource="{Binding Title}" SelectionChanged="ListBox_SelectionChanged" Height="486" Width="404" FontSize="20">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Margin="0,0,10,0" Width="380" Height="140">
<Grid >
<TextBlock Text="{Binding cdata}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}" />
<ListBox Name="ab" ItemsSource="{Binding Description}" FontSize="14">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Width="380" Height="100">
<Grid>
<TextBlock Text="{Binding cdata}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}" />
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
where ListBox "abcd" has to be bound with class title and "ab" to the class Description.Both the classes have just one string field , "cdata".
In the xaml.cs I do :
abcd.ItemsSource=from article in root.openfooty.news.article
select new Classes.Title
{
cdata = article.title.cdata
};
ab.ItemSource = from article in root.openfooty.news.article
select new Classes.Description
{
cdata = article.description.cdata
};
binding with "abcd" works fine but with "ab" it says "the nam ab doesnt exist in the current context"
Any help would be much appreciated. Thanks :D
Why don't you write a single class like this
public class TitleDescription
{
public string title { get; set; }
public string description { get; set; }
}
and try the databinding ?
abcd.ItemsSource=from article in root.openfooty.news.article
select new Classes.TitleDescription
{
title = article.title.cdata,
description = article.description.cdata
};
And have only one list box like this
<ListBox Name="abcd" Margin="10,0,30,0" SelectionChanged="ListBox_SelectionChanged" Height="486" Width="404" FontSize="20">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Margin="0,0,10,0" Width="380" Height="140">
<Grid >
<TextBlock Text="{Binding description}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}" />
<TextBlock Text="{Binding title}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}" />
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I am trying to bind a listbox from 2 tables. These 2 tables are related.
(windows phone project)
XAML:
<ListBox Name="LstOrders" ItemsSource="{Binding}" Margin="12,11,12,12" toolkit:TiltEffect.IsTiltEnabled="True" Height="643">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0">
<TextBlock Text="{Binding refe}"
Tag="{Binding idOrder}"
Margin="0,0,0,0"
FontSize="{StaticResource PhoneFontSizeExtraLarge}"
FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
<TextBlock Text="{Binding tipo}"
Margin="0,0,0,0"
Foreground="{StaticResource PhoneSubtleBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}"/>
<TextBlock Text="{Binding country}"
Margin="0,0,0,0"
Foreground="{StaticResource PhoneSubtleBrush}"
FontSize="{StaticResource PhoneFontSizeNormal}"
FontFamily="{StaticResource PhoneFontFamilySemiBold}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#
EXAMPLE
using (ordersDBDataContext miDataContext = new ordersDBDataContext("Data Source='isostore:/mydatabase.sdf'"))
{
var _lista = from p in miDataContext.orders
join t in miDataContext.tipos on p.idTipo equals t.idTipo
orderby p.refe
where p.idCliente == _idCli
select new
{
p.refe, p.country,p.idOrder,t.tipo
};
this.LstOrders.ItemsSource = _lista;
}
RESULT
No display any data.What is wrong?
iF i doing this I can see that _lista contains correct data:
foreach (var rr in _lista)
{
MessageBox.Show(rr.tipo);
}
You are disposing your DataContext (correctly), but this means when the _lista query is executed the DataContext will no longer be valid and there will be an exception. WPF unhelpfully swallows exceptions in certain circumstances so you probably aren't seeing the exception.
The solution is to use:
this.LstOrders.ItemsSource = _lista.ToList();
and also to either remove ItemsSource={Binding} from your xaml or alternatively leave the binding in and use
this.LstOrders.DataContext = _lista.ToList();
Also, see Silverlight 4 Data Binding with anonymous types which may be relevant to your problem.
I don't know the context of your code snippet but I'm guessing you probably need to call
this.LstOrders.Items.Refresh();
I cant exactly explain why cos I am not familiar with WPF, but in winforms it would have been a DataBind().
I am using List to bind a listbox which is as follows:
<ListBox x:Name="ContentPanel" SelectionChanged="onSelectionChanged" Background="LightGray" Grid.Row="2">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Name="{Binding title}" Height="165" Margin="25,5,25,0" Width="430">
<Border BorderThickness="1" Height="165" BorderBrush="Gray">
<toolkit:ContextMenuService.ContextMenu >
<toolkit:ContextMenu IsZoomEnabled="False">
<toolkit:MenuItem Name="Delete" Header="Delete Message" Click="DeleteMessage_Click" >
</toolkit:MenuItem>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<StackPanel Orientation="Vertical">
<StackPanel>
<TextBlock Text="{Binding title}" Margin="5,0,0,0" FontSize="25" Foreground="Black"/>
<TextBlock Text="{Binding msgFrom}" Padding="5" TextWrapping="Wrap" Foreground="Gray" FontSize="20"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5,13,0,0" FontSize="24" Foreground="WhiteSmoke" Text="{Binding msgReceivedOn}"/>
<toolkit:ToggleSwitch Margin="170,10,0,0" IsChecked="{Binding msgStatus}" Unchecked="UnChecked" Background="LightBlue" Checked="Checked"/>
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
At first data is successfully loaded. But when I use the Contextmenu to remove the item and reload the listbox.. it fires an exception. Code to handle the context menu click is:
private void DeleteMessage_Click(object sender, RoutedEventArgs e)
{
MenuItem item = sender as MenuItem;
Message message = (Message)item.DataContext;
MessageBoxResult result = MessageBox.Show("Are you sure to delete the message??", "Confirmation", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
return;
else
{
ContentPanel.Items.Remove(message);
lstMessage.Remove(message);
}
ContentPanel.ItemSource = lstMessage;
}
But it this code is not working. So any suggestions?
You don't need each time to bind collection to a list. Also, when you remove an item from your collection, it should disappear also in the list (if binding setup properly). I think you have not ObservableCollection, so you need manage items manually. Please, consider to use ObservableCollection.
Your code should looks like:
lstMessage.Remove(message); //it must raises CollectionChanged event automatically
And this lines is unnecessary:
ContentPanel.Items.Remove(message);
ContentPanel.ItemSource = lstMessage;
I would like to make a horizontal listbox that could be infinite scrolling (looping listbox/scrollviewer, or circular listbox/scrollviewer), means that when I scroll to its end, its would scroll over from beginning.
I have tried to make the listbox horizontal, but it wouldn't scroll so I put it inside a scrollviewer to have it scroll horizontally. However it's not the listbox that scroll and I need them somehow to scroll over from beginning.
This is what I have so far:
private void DoWebClient()
{
var webClient = new WebClient();
webClient.OpenReadAsync(new Uri("http://music.mobion.vn/api/v1/music/userstop?devid="));
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (var reader = new StreamReader(e.Result))
{
string s = reader.ReadToEnd();
Stream str = e.Result;
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("user")
select new mobion
{
avlink = (string)query.Element("user_info").Element("avlink"),
nickname = (string)query.Element("user_info").Element("nickname"),
track = (string)query.Element("track"),
artist = (string)query.Element("artist"),
};
listBox.ItemsSource = data;
}
}
Mainpage.xaml
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid/>
</DataTemplate>
<Storyboard x:Name="Storyboard1" RepeatBehavior="forever" Completed="Storyboard1_Completed">
<DoubleAnimation Duration="0:0:25" To="-2400" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="imagesScrollview" d:IsOptimized="True"/>
</Storyboard>
</phone:PhoneApplicationPage.Resources>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Margin="8,563,-2400,2" Width="auto" x:Name="imagesScrollview" Opacity="1" Background="#FF3ED216" Grid.Row="1" RenderTransformOrigin="0.5,0.5">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<im:ControlStoryboardAction Storyboard="{StaticResource Storyboard1}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ScrollViewer.RenderTransform>
<CompositeTransform/>
</ScrollViewer.RenderTransform>
<ListBox x:Name="listBox" Width="Auto" Height="Auto" Background="#FF3ED216" ManipulationCompleted="listBox_ManipulationCompleted">
<ListBox.RenderTransform>
<CompositeTransform/>
</ListBox.RenderTransform>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.RenderTransform>
<TranslateTransform X="0" />
</StackPanel.RenderTransform>
</StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="15,0">
<Image Name="imageAV" Source="{Binding Path=avlink}" Height="80" Width="80" Stretch="UniformToFill" MouseLeftButtonUp="imageAV_MouseLeftButtonUp" ImageFailed="imageAV_ImageFailed" />
<StackPanel Orientation="Vertical" Margin="10,0,0,0" MouseLeftButtonUp="StackPanel_MouseLeftButtonUp">
<TextBlock Name="indexTextBlock" Text="{Binding num}" />
<TextBlock Text="{Binding nickname}"/>
<TextBlock Text="{Binding track}" FontWeight="Bold" />
<TextBlock Text="{Binding artist}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
To make a listbox scroll horizontally you need to set the ScrollBar Visibility properties of the internal ScrollViewer.
Like this:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Disabled" >
The Toolkit includes a LoopingSelector class that you could based your own control implementation on. There's an example of creating such a control at http://babaandthepigman.wordpress.com/2010/09/22/wp7-looping-selector/ (although it is for a vertical list)
Not sure if that helps, but the standard approach to infinite scrolling is to put at least one screenful of duplicate items from the beginning of the list at the end, and upon reaching the end, transparently skip (1-step scroll) to the beginning or a fixed short offset from it (and vice versa) so that it looks the same but the user looks at the items from the beginning of the list, not their duplicates from the end.