UWP Custom ListView to scroll down - mvvm

So, I have a listview and I want it whenever an item is created to scroll to that item (bottom). Because I am using MVVM I found really nice explanation on how to make a new control that inherits from listview that scrolls down. The problem is that this answer (the third) is referring to WPF 6 years ago.
I am making a UWP app, so I copied the code and tried to format it to my needs. The following code doesn't give any error or exception but instead it loads the "ChatListView" as I call it perfectly and then does nothing. The comments are only a bit edited compared to the original code.
What can I do ? Thank you in advance!
public class ChatListView : ListView
{
//Define the AutoScroll property. If enabled, causes the ListBox to scroll to
//the last item whenever a new item is added.
public static readonly DependencyProperty AutoScrollProperty =
DependencyProperty.Register(
"AutoScroll",
typeof(Boolean),
typeof(ChatListView),
new PropertyMetadata(
true, //Default value.
new PropertyChangedCallback(AutoScroll_PropertyChanged)));
//Gets or sets whether or not the list should scroll to the last item
//when a new item is added.
public bool AutoScroll
{
get { return (bool)GetValue(AutoScrollProperty); }
set { SetValue(AutoScrollProperty, value); }
}
//Event handler for when the AutoScroll property is changed.
//This delegates the call to SubscribeToAutoScroll_ItemsCollectionChanged().
//d = The DependencyObject whose property was changed.</param>
//e = Change event args.</param>
private static void AutoScroll_PropertyChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SubscribeToAutoScroll_ItemsCollectionChanged(
(ChatListView)d,
(bool)e.NewValue);
}
//Subscribes to the list items' collection changed event if AutoScroll is enabled.
//Otherwise, it unsubscribes from that event.
//For this to work, the underlying list must implement INotifyCollectionChanged.
//
//(This function was only creative for brevity)
//listBox = The list box containing the items collection.
//subscribe = Subscribe to the collection changed event?
private static void SubscribeToAutoScroll_ItemsCollectionChanged(
ChatListView listView, bool subscribe)
{
INotifyCollectionChanged notifyCollection =
listView as INotifyCollectionChanged;
if (notifyCollection != null)
{
if (subscribe)
{
//AutoScroll is turned on, subscribe to collection changed events.
notifyCollection.CollectionChanged +=
listView.AutoScroll_ItemsCollectionChanged;
}
else
{
//AutoScroll is turned off, unsubscribe from collection changed events.
notifyCollection.CollectionChanged -=
listView.AutoScroll_ItemsCollectionChanged;
}
}
}
//Event handler called only when the ItemCollection changes
//and if AutoScroll is enabled.
//sender = The ItemCollection.
//e = Change event args.
private void AutoScroll_ItemsCollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
int count = Items.Count;
ScrollIntoView(Items[count - 1]);
}
}
//Constructor a new ChatListView.
public ChatListView()
{
//Subscribe to the AutoScroll property's items collection
//changed handler by default if AutoScroll is enabled by default.
SubscribeToAutoScroll_ItemsCollectionChanged(
this, (bool)AutoScrollProperty.GetMetadata(typeof(ChatListView)).DefaultValue);
}
}

If you want to create a chat application you can use the ItemsStackPanel's ItemsUpdatingScrollMode particular property to KeepLastItemInView value to scroll to the latest item.
Usage:
<ListView>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsStackPanel ItemsUpdatingScrollMode="KeepLastItemInView" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
Note: KeepLastItemInView enum member was introduced in the 14393 SDK.
Related link:
https://learn.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.Controls.ItemsStackPanel#properties_

The accepted answer is pretty nice. However I there is one thing it won't do (at least if I simply copy and paste the above XAML): it won't do its intended scrolling if, say, the user was away from that page while new items were added, and then they navigated to the page.
For that I had to hook into
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (MyListView.Items.Count == 0)
return;
object lastItem = MyListView.Items[MyListView.Items.Count - 1];
MyListView.ScrollIntoView(lastItem);
}

Related

How to don't validate form with Ajax buttons

I have a problem with validation on form actually sub-form.
In my website I have some kind of table and "Add row" button (BlockingAjaxSubmitLink).
When I try add let say 2 rows, I get validation error (because row in this table has Required=True parameter) and I can't add another row. I tried use simple AjaxLink but it doesn't have reference to form in onClick method and when I complete some rows and click "Add row" this data get lost.
I want to enable validation only after "save" button click.
Any idea how to deal with this problem?
I do something like you want using an AjaxLink.
My AjaxLink:
private AjaxLink addNewRow = new AjaxLink("addNewRow") {
#Override
public void onClick(AjaxRequestTarget target) {
MyEntityObject newTableRowObject = new MyEntityObject(irrelevantParameter);
entityObjectTableService.createNewRowInDB(newTableRowObject );
target.add(listViewContainer);
}
};
In this code the listViewContainer is a WebMarkupContainer which contains a ListView holding the table rows.
When i click this AjaxLink a new object representing a row in my table is added to the database and then the container containing the ListView is being refreshed refreshing the ListView and the new empty object is being fetched from the DB and shown as a new row in my table at the end.
Depending on your structure maybe you are looking after disabling validation using setDefaultFormProcessing(true); - http://ci.apache.org/projects/wicket/apidocs/6.x/org/apache/wicket/markup/html/form/AbstractSubmitLink.html#setDefaultFormProcessing%28boolean%29
For now I write some kind of hack
First I set
addKnowledgeLink.setDefaultFormProcessing(false);
and next
BlockingAjaxSubmitLink<Object> addKnowledgeLink = new BlockingAjaxSubmitLink<Object>(
"link_knowledge_add") {
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ChangeDataForm.this.process(this);
/* some code */
target.add(form.get(MY_CONTAINER_ID));
}
(...)
and my hack...
//HACK
public void process(IFormSubmitter object){
if (!isEnabledInHierarchy() || !isVisibleInHierarchy())
{
return;
}
// run validation
validate();
/*if (hasError())
{
// mark all children as invalid
markFormComponentsInvalid();
// let subclass handle error
callOnError(object);
}
else
{*/
// mark all children as valid
markFormComponentsValid();
// before updating, call the interception method for clients
beforeUpdateFormComponentModels();
// Update model using form data
updateFormComponentModels();
// validate model objects after input values have been bound
onValidateModelObjects();
if (hasError())
{
callOnError(object);
return;
}
// Form has no error
delegateSubmit(object);
//}
}
and I ovveride one method
#Override
protected void onError(){
super.onError();
this.updateFormComponentModels();
}
I know it is ugly solution but I couldn't figure out anything better..
And I couldn't shutdown feedback messages

How to automatically check the checkboxes in the gridview when displaying?

I'm using GXT 3 to build a GridView that will display "incidents".
What I want to do is that when it renders it, I want some checkboxes to be checked, others to empty, according to the boolean in the database.
Below you have my code:
CheckBoxSelectionModel<IncidentDto> isIncidentCM = new CheckBoxSelectionModel<IncidentDto>(incidentProperties.incident());
allColumns.add(isIncidentCM.getColumn());
ColumnModel<IncidentDto> columnModel = new ColumnModel<IncidentDto>(allColumns);
final Grid<IncidentDto> grid = new Grid<IncidentDto>(store, columnModel);
grid.setSelectionModel(isIncidentCM);
add(grid);
And the IncidentProperties value provider:
IdentityValueProvider<IncidentDto> incident();
I'm not sure if you can bind the selection value to a boolean property, but you could add a listener to the Grid to update the checkboxes based on the boolean condition.
grid.addBeforeShowHandler(BeforeShowEvent event) {
#Override
public void onBeforeShow(BeforeShowEvent event) {
List<IncidentDto> itemsToSelect = new ArrayList<IncidentDto>();
for (IncidentDto incident : store.getAll()) {
if (incident.getBooleanProperty()) { //whatever your property is called
itemsToSelect.add(incident);
}
}
isIncidentCM.setSelection(itemsToSelect);
}
}
There may be other implications in using a BeforeShowEvent depending on how/when you populate your store, render the grid, etc. but assuming your store is fully loaded and the property available from your store objects I believe this should accomplish your goal.

GWT CellBrowser- how to always show all values?

GWT's CellBrowser is a great way of presenting dynamic data.
However when the browser contains more rows than some (seemingly) arbitrary maximum, it offers a "Show More" label that the user can click to fetch the unseen rows.
How can I disable this behavior, and force it to always show every row?
There are several ways of getting rid of the "Show More" (which you can combine):
In your TreeViewModel, in your NodeInfo's setDisplay or in the DataProvider your give to the DefaultNodeInfo, in onRangeChange: overwrite the display's visible range to the size of your data.
Extend CellBrowser and override its createPager method to return null. It won't change the list's page size though, but you can set it to some very high value there too.
The below CellBrowser removes the "Show More" text plus loads all available elements without paging.
public class ShowAllElementsCellBrowser extends CellBrowser {
public ShowAllElementsCellBrowser(TreeViewModel viewModel, CellBrowser.Resources resources) {
super(viewModel, null, resources);
}
#Override
protected <C> Widget createPager(HasData<C> display) {
PageSizePager pager = new PageSizePager(Integer.MAX_VALUE);
// removes the text "Show More" during loading
display.setRowCount(0);
// increase the visible range so that no one ever needs to page
display.setVisibleRange(0, Integer.MAX_VALUE);
pager.setDisplay(display);
return pager;
}
}
I found a valid and simple solution in setting page size to the CellBrowser's builder.
Hope this will help.
CellBrowser.Builder<AClass> cellBuilder = new CellBrowser.Builder<AClass>(myModel, null);
cellBuilder.pageSize(Integer.MAX_VALUE);
cellBrowser = cellBuilder.build();
The easiest way to do this is by using the:
cellTree.setDefaultNodeSize(Integer.MAX_VALUE);
method on your Cell Tree. You must do this before you begin expanding the tree.
My workaround is to navigate through elements of treeview dom to get "show more" element with
public static List<Element> findElements(Element element) {
ArrayList<Element> result = new ArrayList<Element>();
findShowMore(result, element); return result; }
private static void findShowMore(ArrayList res, Element element) {
String c;
if (element == null) { return; }
if (element.getInnerText().equals("Show more")) { res.add(element);
}
for (int i = 0; i < DOM.getChildCount(element); i++) { Element
child = DOM.getChild(element, i); findShowMore(res, child); } }
and than use:
if (show) { element.getStyle().clearDisplay(); } else {
element.getStyle().setDisplay(Display.NONE); }

GWT/MVP: detecting change events in a table with proper MVP pattern

We're using gwt-presenter, but not really a question specific to that...
I've got a table with users in it. As I build the table in the view (from the data provided by the presenter), I need to add two action buttons ("Edit", and "Delete") at the end of the row.
What's the best way to assign click handlers to these buttons so the presenter knows which was clicked? Previous to this, we could pass a private field from the view to the presenter and attach a discrete click handler to that button. However, this method is rather rigid and doesn't work in this scenario very well.
Thanks in advance.
How about having the view allowing the subscription for edit/delete click events, registering internally the individual row click events, and then delegating the event handling to the ones registered by the view?
I mean something like the following pesudo code:
View:
addRowEditClickHandler(ClickHandler handler) {
this.rowEditClickHandler = handler;
}
addRowDeleteClickHandler(ClickHandler handler) {
this.rowDeleteClickHandler = handler;
}
//... somewhere when setting up of the grid...
rowEditButton.addClickHandler = new ClickHandler() {
onClick(args) {
this.rowEditClickHandler.onClick(args)
}
rowDeleteButton.addClickHandler = new ClickHandler() {
onClick(args) {
this.rowDeleteClickHandler.onClick(args)
}
Presenter:
View view = new View();
view.addRowEditClickHandler( new ClickHandler() {
onClick(args) {
doSomething();
}
});
view.addRowDeleteClickHandler( new ClickHandler() {
onClick(args) {
doSomething();
}
});

HierarchicalDataBoundControl.PerformDataBinding not being called on postback

I am binding to a SiteMapDataSource (hierarchical).
I am overriding PerformDataBinding to grab the data from the datasource.
Everything works great on page load. But when I perform a postback anywhere on the page, the PerformDataBinding method does not get called, and in effect, not rendering any menu items (PerformDataBinding wasn't called).
No clue why this is happening, but I have a fix for it. Amazingly, every example of a HierarchicalDataBoundControl I could find (even from msdn) was doing this. However, here is a workaround.
private bool dataBound = false;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.Page.IsPostBack)
{
this.DataBound += delegate { dataBound = true; };
this.Page.Load += delegate { if (!dataBound) DataBind(); };
}
}