<ListView x:Name="myListView" ItemsSource="{x:Bind PageViewModel.myCollectionOfThings, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="viewmodels:ThingViewModel>
<TextBlock Text="{x:Bind Name, Mode=OneWay}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Name="TestButton" Tapped="TestButton_Tapped"/>
private void TestButton_Tapped(object sender, TappedRoutedEventArgs e)
{
PageViewModel.myCollectionOfThings.Add(newItem);
myListView.SelectedIndex++;
}
I'm trying to create a carousel control**. Using the code above I can dynamically add an item to the end of the collection each time its selected index increases. It works as one would expect except one problem. Even though the UI is reflecting the new items added to the end of the ListView, if I iterate past the last index of the original collection size, the UI jumps back to the beginning of the list and the selected index becomes 0. I've tried many variations of the above code and tried different collection types. I've also tried re-assigning the ListView's ItemSource each iteration which didn't do anything. Any help would be appreciated.
**I know there's something called Carousel in the UWP Community Toolkit but it isn't actually a carousel. A carousel can scroll endlessly as its collection will loop, which that control does not do.
If you want Carousel that can scroll endlessly then take a look at the Carousel control in the Windows AppStudio NuGet package. Download Windows App Studio UWP Samples to learn about the control.
Here an image of this Carousel Control
It looks like the listview is rebinding with binding source when the collection is changed. Try to re-set the index manually after adding the item.
int currentIndex = myListView.SelectedIndex;
PageViewModel.myCollectionOfThings.Add(newItem);
myListView.SelectedIndex = currentIndex++;
// If above doesn't work try setting selectedItem property to newItem.
Related
I have a ListView which ItemSource is bind to an ObservableCollection. This collection stores a list of some user's chat messages. Now I want to shift that item on top whenever that user receives a new chat message. Likewise in WhatsApp and slack app. So I want to know what is the correct way of doing this. Right now I am removing an item from the list and then adding it to the 0th index but this way sometimes I am getting parameter incorrect issues. So is there any way so that I can directly shift any chat to the top without removing it.
Xaml code for listview is below:
<ListView MaxHeight="{x:Bind ViewModel.OpenedChatMaxHeight, Mode=OneWay}"
Margin="0,10,0,0"
CanDragItems="True"
Loaded="{x:Bind ViewModel.OpenedChatDataLoaded}"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
SelectedIndex="{x:Bind ViewModel.OpenChatListSeletedItem,Mode=TwoWay}"
ItemsSource="{x:Bind ViewModel.OpenChatList,Mode=TwoWay}"
SelectionChanged="{x:Bind ViewModel.ChatSelected}"
IsItemClickEnabled="True"
ItemClick="{x:Bind ViewModel.OpenPinnedChatListItemClick}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel ItemsUpdatingScrollMode="KeepItemsInView" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
The ObservableCollection<T> class has a Move method that you can use to move an item from one index to another:
OpenedChatMaxHeight.Move(oldIndex, 0);
This is more convenient than manually removing and adding the item back at index 0.
I have tried the Move method but in that case, I always get index out of range error my view just gets out of focus.
Move method will moves the item at the specified index to a new location in the collection. Please add debug point to check if the oldIndex is correct. Above problem looks you have not get correct oldindex.
Is there a feature to shift item on top in a listview
For fixing the chart item in the top, we often make a separate top list. When you want to fix the chart item, you could remove it from the previous chart list, and add it into top list.
For this way, it is easy to make a istop style, but not make datatemplete selector for previous list. And you could also store the istop chart items in local storage to improve rendering performance.
I have 2 ListView controls bound to 2 different ObservableCollection<string> like this:
<ListView x:Name="List1"
Grid.Column="0"
CanDragItems="True"
CanReorderItems="True"
AllowDrop="True"/>
<ListView x:Name="List2"
Grid.Column="1"
CanDragItems="True"
CanReorderItems="True"
AllowDrop="True"/>
When dragging and dropping items in their own respective lists I get the default animation like this:
But I cannot get the same animation when I hover over the second ListView. Why is that and how can I invoke the same animation in this case? I can handle what happens on drop but first I need to be able to invoke the same animation.
All current solution I have gone through does not have the animation or uses some other library/control to substitute for this. Any help or suggestion regarding this is appreciated.
There is no default drop animation for a ListView. You'll need to create something yourself - or use a third party solution such as you report to have already found.
I'm trying to find the best solution for a TabControl that both support a close button on each TabItem, and always show a "new tab button" as the last tab.
I've found some half working solutions, but i think that was for MVVM, that I'm not using. Enough to try to understand WPF =)
This is the best solution I've found so far:
http://www.codeproject.com/Articles/493538/Add-Remove-Tabs-Dynamically-in-WPF
A solution that i actually understand. But the problem is that it is using the ItemsSource, and i don't want that. I want to bind the ItemsSource to my own collection without having to have special things in that collection to handle the new tab button.
I've been search for days now but cant find a good solution.
And I'm really new to WPF, otherwise i could probably have adapted the half done solutions I've found, or make them complete. But unfortunately that is way out of my league for now.
Any help appreciated.
I have an open source library which supports MVVM and allows extra content, such as a button to be added into the tab strip. It is sports Chrome style tabs which can tear off.
http://dragablz.net
This is bit of a dirty way to achieve the Add (+) button placed next to the last TabItem without much work. You already know how to place a Delete button next to the TabItem caption so I've not included that logic here.
Basically the logic in this solution is
To bind ItemsSource property to your own collection as well as
the Add TabItem using a CompositeCollection.
Disable selection of
the Add(+) TabItem and instead perform an action to load a new tab when it
is clicked/selected.
XAML bit
<TextBlock x:Name="HiddenItemWithDataContext" Visibility="Collapsed" />
<TabControl x:Name="Tab1" SelectionChanged="Tab1_SelectionChanged" >
<TabControl.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding DataContext.MyList, Source={x:Reference HiddenItemWithDataContext}}" />
<TabItem Height="0" Width="0" />
<TabItem Header="+" x:Name="AddTabButton"/>
</CompositeCollection>
</TabControl.ItemsSource>
</TabControl>
The code behind
private void Tab1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Contains(AddTabButton))
{
//Logic for adding a new item to the bound collection goes here.
string newItem = "Item " + (MyList.Count + 1);
MyList.Add(newItem);
e.Handled = true;
Dispatcher.BeginInvoke(new Action(() => Tab1.SelectedItem = newItem));
}
}
You could make a converter which appends the Add tab. This way the collection of tabs in you viewmodel will only contain the real tabs.
The problem is then how to know when the Add tab is selected. You could make a TabItem behavior which executes a command when the tab is selected. Incidentally I recommended this for another question just recently, so you can take the code from there: TabItem selected behavior
While I don't actually have the coded solution, I can give some insight on what is most likely the appropriate way to handle this in a WPF/MVVM pattern.
Firstly, if we break down the request it is as follows:
You have a sequence of elements that you want to display.
You want the user to be able to remove an individual element from the sequence.
You want the user to be able to add a new element to the sequence.
Additionally, since you are attempting to use a TabControl, you are also looking to get the behavior that a Selector control provides (element selection), as well as an area to display the element (content) which is selected.
So, if we stick to these behaviors you'll be fine, since the user interface controls can be customized in terms of look and feel.
Of course, the best control for this is the TabControl, which are you already trying to use. If we use this control, it satisfies the first item.
<TabControl ItemsSource="{Binding Path=Customers}" />
Afterwards, you can customize each element, in your case you want to add a Button to each element which will execute a command to remove that element from the sequence. This will satisfy the second item.
<TabControl ...>
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=CustomerId}" />
<Button Command="{Binding Path=RemoveItemCommand, Mode=OneTime,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TabControl}}"
CommandParameter="{Binding}" />
</StackPanel>
</DataTemplate>
<TabControl.ItemTemplate>
</TabControl>
The last part is a bit more difficult, and will require you to actually have to create a custom control that inherits from the TabControl class, add an ICommand DependencyProperty, and customize the control template so that it not only displays the TabPanel, but right next to it also displays a Button which handles the DependencyProperty you just created (the look and feel of the button will have to be customized as well). Doing all of this will allow you to display your own version of a TabControl which has a faux TabItem, which of course is your "Add" button. This is far far far easier said than done, and I wish you luck. Just remember that the TabPanel wraps onto multiple rows and can go both horizontally or vertically. Basically, this last part is not easy at all.
I have a list view that I want to scroll to the bottom as I add items into the "Items" list.
As I add items they appear in the ListView, but when I reach the limit of the screen, the list remains showing the top section and new items are added to the bottom. If I scroll down I can see the new items. I'd like it to auto scroll to the bottom so that I can always see the latest items in the list.
<ListView
x:Name="lvBasketContent"
Grid.Row="1"
ItemsSource="{Binding Items}"
ItemContainerStyle="{StaticResource ListViewItemStyle1}"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Bottom"
SelectionMode="None"
IsSwipeEnabled="False"
VerticalAlignment="Top"
>
Can anyone help me out please?
You need to create a custom behavior or derived implementation of ListView.
This class should monitor the ItemsSource collection for changes and call ListViewBase.ScrollIntoView(Object), passing in the item that you want to show. In your case, this may be the last one added.
I recommended the behavior as it keeps your code modular as you can use it on any listview in your solution by changing the xaml only.
I'm not going to write the code for you as behaviors are a very useful technique to learn first hand. The first link should give you all you need to get cracking.
Do you can try put this in your code ? Each time you add an item to your listbox , try call it
//Add an item in the listbox
lvBasketContent.Items.Add(...);
//...
//Scroll to bottom
lvBasketContent.SelectedIndex = lvBasketContent.Items.Count -1
lvBasketContent.ScrollIntoView(lvBasketContent.SelectedItem)
I am writing a windows-phone 7 application. I've got a page with a list of TextBlock(s) contained in a ListBox. The behavior I want is that upon clicking one of those TextBlock(s) the page is redirected to a different one, passing the Text of that TextBlock as an argument.
This is the xaml code: (here I am binding to a collection of strings, and the event MouseLeftButtonDown is attached to each TextBlock).
<ListBox x:Name="List1" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock MouseLeftButtonDown="List1_MouseLeftButtonDown" Text="{Binding}"
FontSize="20"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But this has been unsuccessful for me. I have tried attaching MouseLeftButtonDown event to either the individual TextBox(es) or to the ListBox. And I have had exceptions raised as soon as I use NavigationService.Navigate(uri). Which event should be attached? Should the event be attached to the individual items or to the list as a whole?
I have found a way to work around this problem by populating ListBox with HyperlinkButton(s). However, I would like to understand why the TextBox approach did not work.
This is my first attempt with Silverlight, so I might be missing something basic here.
There are a few ways to do this but I'll walk you through one of the the simplest (but not the purest from an architectural perspective).
Basically you want to find out when the selection of the ListBox changes. The ListBox raises a SelectionChanged event which can be listened to in the code behind.
<ListBox x:Name="List1" ItemsSource="{Binding}" SelectionChanged="SelectionChangedHandler" SelectionMode="Single" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontSize="20"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Then have a handler something like:
private void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
IList selectedItems = e.AddedItems;
string val = selectedItems.OfType<string>().FirstOrDefault();
NavigationService.Navigate(new Uri(val));
}
One thing you'll need to be aware of is that ListBoxes support multiple selection. For this reason, the event arguments give you back a list of the selected items. For simplicity, all I've done is taken the first value from this list and used that as the navigation value. Notice how I've also set the SlectionMode property of the ListBox to Single which will ensure the user can only select one item.
If I were doing this for real I'd look into creating an TriggerAction tat can be hooked up to an event trigger through xaml which will remove the for code behinds. Take a look at this link if you're interesetd.
In addition to Chris' and James' replies, I'd add that you will also need to clear the listbox selection in the event handler, otherwise the user won't be able to tap the same item twice on the listbox (because the item will already be selected).
Using James' approach, I would change the SelectionChangedHandler() implementation as follows:
private void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
// Avoid entering an infinite loop
if (e.AddedItems.Count == 0)
{
return;
}
IList selectedItems = e.AddedItems;
string val = selectedItems.OfType<string>().FirstOrDefault();
NavigationService.Navigate(new Uri(val));
// Clear the listbox selection
((ListBox)sender).SelectedItem = null;
}
What I would recommend is binding the SelectedItem property of the ListBox to a property in your ViewModel. Then, on the ListBox's SelectedItemChanged event, navigate to to the appropriate URL passing the data key on the QueryString, or upgrade to something like MVVM Light and put the actual SelectedItem object on the message bus for the child window to pick up. I have a sample of this second method on my Skydrive that you can check out.
HTH!
Chris