I have a MVVM (Prism) application that I need to implement a master details screen wheer the master is a listview and the details is displayed next to it. Read-only seems easy enough (haven't done it yet but I've got my head around WPF binding) but edit/add confuses me.
How to I make it so the master is not updated until the details is saved?
How do I make it so you can't change the master's current selection while in edit/add mode?
I've been googling a plenty but have not found any meaty examples of this.
Thanks.
PS: This view is a child view on a larger screen. This is why I want both master and detail together.
You certainly can do this, though in my opinion such a UI design fails to harness the full power of WPF. Old WinForms UIs usually didn't update most of the application until data was saved to SQL Server (or wherever) because they didn't have real business objects and a powerful binding system like WPF. Trying to copy WinForms limitations within WPF seems like a step backward to me. Why not show the latest data everywhere it is visible in the UI, including in the master view? Also, why not allow the user to edit multiple items before saving, for example marking any edited but unsaved item with an animated marker in the master view? Combine these with a generalized undo and you have a better design and more intuitive for the user.
However if your business requirements make it absolutely necessary, here is how to do it:
Preventing changes to data from being visible outside the detail until it is saved
Upon entry into your "edit/add mode", make a copy of the data objects and set your detail view's DataContext to the copy instead of the live object. When the data is "saved", copy the data from the shadow copy back into the live object and set your detail view's DataContext back where it should be.
Preventing the master's current selection from changing while in edit/add mode
Two possibilities:
During edit/add mode, change the master view to disallow mouse hit testing or keyboard focus
When edit/add mode begins, capture the "current selection" then add an event handler that watches for "current selection" changes and immediately changes the selection back to what it was. When edit/add mode ends, remove the handler. This handler can be conveniently coded using a lambda expression and using a closure on a local variable to store the current selection.
Thanks for the answer. Now I've re-read my message, I see it is rather vague. I have a screen that edits an object which contains multiple lists of other child objects. I've implemented these as different tabs in a tab control. One of these tabs edits the comments, so I wanted to display a list of comments with an edit panel for the current selection next to the list. The user could then use add, edit or delete buttons to update the list. I wanted to do this in a pure(ish) MVVM way.
I came up with the following design which seems to work with minimal hacks.
The View includes a list of the child objects simply as a ListView bound to an observable collection within the ViewModel. I included a child object buffer – this is used to buffer changes until they are ready to be saved back to the list (or thrown away).
The View also includes an edit panel bound to the buffer object in the ViewModel. The buffer is updated whenever the list view’s current selection changes using a deep copy. I tried using data binding on the Selecteditem property but the set was never called, so a small code-behind method was added to force the property to be updated when the selection was changed.
The list view and edit view are mutually exclusive. In theory you could hide the disabled one, perhaps using a flip screen. As a general pattern, it is better for my app to have both visible at the same time as the edit panel may show extra information not shown in the list view. The choice as to which panel is enabled is controlled by binding IsEnabled to a ViewModel property like IsEditCommentMode.
Commands to manage the list have to be added, these are New, Editand Delete. Note that Add and Edit will set set up the buffer then set IsEditCommentMode to true. These list management commands are only available when IsEditCommentMode is false.
The edit panel implements Save and Cancel commands, they are only be enabled when IsEditCommentMode is true. When Save is executed, it should copy from the buffer to the list (either add or update) and fire the change notification. Finally, it should set IsEditCommentMode to false.
This all works well and does not seem to violate any MVVM tenents (in my humble but often flawed opinion).
Related
I started a project using TemplateStudio for WinUI (C#) 5.2. It uses the CommunityToolkit ListDetailsView Control for a "List Details" page.
What is the best way to load additional data when a user selects something from the list of results? I thought I would add two more properties to my ViewModel (one to handle the data, one to show a busy animation while the data is loading, both using ObservableObjects SetProperty), when the selected gets changed I fetch the data async for the selected item and update the ViewModel properties accordingly.
I can't seem to find a way how to access this data from the DetailsViewControl, and I'm not sure I do it the correct way anyway.
If I add a property to my model and change the value on changing the selected the data gets added, but the UI doesn't update itself (I tried _selected and Selected). Only when selecting another item from the results and going back to the previous shows the value.
What would be the best/correct way to lazy load additional data with this control? There would be about 4-5 parallel requests going on in the first release.
Later on I need a few buttons in the DetailsViewControl as well, where and how am I supposed to handle the commands?
Or am I better of not using this control and do it manually?
I frequently have the following task:
I have a collection of objects (f.e. Customers) and want to provide the user with an editor for these objects. Typically I have some list control on the left side of the editor and a form on the right side. The form displays the properties of the object that is currently selected on the left side.
Regarding the confirmation of any changes, there are at least two strategies:
make the editor a modal dialog window and give it OK/Cancel buttons. On OK save all changes for all objects
give the editor a Save button above or below the form on the right side that would allow the user to confirm changes to the currently selected object.
My question is about the second strategy, implemented as an MVVM application with WPF:
I would like to give my user a feedback that there are unsaved changes. Applications like text editors often solve this by enabling the Save button when any changes occurred and disabling it again once the user pressed it to confirm her/his changes.
If I understand correctly I would have to monitor changes to any bound properties in my form (backed by a model class). Usually my model classes use auto properties (no explicit getters and setters). Do I have to write explicit getters for all my properties to enable the Save button when anything changed, or is there a smarter way to achieve this?
Following the MVVM pattern, your ViewModels should implement INotifyPropertyChanged interface, than you can easily subscribe to PropertyChanged event and monitor properties changes
If you don't want to write INPC aware getters and setters in your model classes, then another way is to write a equality compare method instead, and then have your save command availability callback call into that to compare the "live" object with the edited one. I'm assuming you have a cloned object that is being edited in order to rollback if the user chooses not to save.
WPF will call it automatically as the user clicks around and types, or you can give it a hint with CommandManager.InvalidateRequerySuggested()
Ok, this is going to be a 1000ft long question, but there's a lot to cover so here goes:
I am creating a paged items control, the purpose of which is to display very large collections in a paged format. I've created a repository on GitHub which can be found here. I have removed any styling for simplicity.
Upon starting the application, it looks like this:
This is pretty straightforward really, there's navigation buttons, an items per page selector but that isn't really important. The problem here is when you click the button "Open New Window".
This will open a new MainWindow, but on the first window, the collection disappears, as shown below:
The image above shows the old window in front, as you can see, there is no list of content as there is on the new window.
So, after smashing my head against a wall for a couple of hours, I am in need of assistance. I'll provide an overview of how the project is structured.
AnagramPagedItemsControl
The control being used for displaying the content is a custom control called AnagramPagedItemsControl, it is responsible for handling navigation between pages. I think the key property here is the PagedCollection.
The PagedCollection dependency property holds the collection which is bound to the Models property in the TestItemsViewModel.
TestItemsViewModel
This is the DataContext of the MainWindow, each window instance should create it's own view model. The CreateTestItems() method is responsible for creating the list of test items.
LazyPagedCollection
The purpose of this collection is to encapsulate the logic of a paged observable collection, it only loads pages when they are needed, hence the laziness.
It exposes methods like NextPage which are called in the AnagramPagedItemsControl when the user clicks on the various navigation buttons. The view model can also call navigation on the LazyPagedCollection, this allows the view model to call navigation without having to go through the view to do it.
TL;DR
When I create a new Window, the content of the previous window disappears. The problem is almost certainly with the control however I am stuck as to how to fix the problem.
This is quite a large problem to look at so I'd be very grateful for anyone who can look into it. Again, the source code is here, please feel free to suggest alternatives or pick out anything that I may have overlooked.
Had some time to spare, so:
The problem is the setter for the CollectionView property in the style for AnagramPagedItemsControl in generic.xaml.
This does not instantiate a new ListBox every time the style is applied; it will just create the one ListBox, the first time the style is created, and use that value over, and over again. So in effect, every instance of MainWindow shares the same ListBox.
You can see this by setting the Tag property of PART_CollectionView to (for instance) "1" in SetupBindings(ItemsControl PART_CollectionView). When you open a new window, you'll see that PART_CollectionView.Tag contains the same value you previously assigned.
EDIT: I needed to skip control creation during post back -- see my answer below.
I'm working on a very basic front end to a simple tool and I wanted to present some data in a much more sorted and useful way, instead of making one huge wall of text. I found this tutorial on building a simple tabbed interface using MultiView, but have run into a bizarre problem. I can't use Ajax tabs because of legal hissy fits over 3rd party software.
My webpage is a basic ASP.NET page with a user control plopped in the middle of it. In this control's ascx file, I defined the Menu (empty) and the MultiView (also empty) so that I can dynamically populate the tabs with content driven from an external file.
When the default page's OnInitComplete function is called, I call through to the user control to load the data file, then build out the tabs and the view content based on the loaded data. I tried doing this from PageLoad, PreInit, and CreateChildControls, but I kept getting an errors saying that I was setting the the MultiView's active view index at an invalid time (and also that there were 0 views despite the fact I just added a bunch of them):
ActiveViewIndex is being set to '0'. It must be smaller than the
current number of View controls '0'. For dynamically added views, make
sure they are added before or in Page_PreInit event.
But OnInitComplete appears to work just fine, so I went with that.
I iterate over the loaded data (multiple lists of strings), and for each list, I add a MenuItem with the list's title to the Menu and a View to the MultiView. The View is populated with a table->row->cell as in the above tutorial. In the cell, I add the list title and a CheckBoxList data bound to the list of strings.
So far so good, but when I click on a tab (or one of the checkboxes, etc) and there is a postback or something like that (the screen flashes as the site redraws itself), there is now a duplicate set of MenuItems immediately after the original. Each time I click on a tab or checkbox, another set of menu items are added.
I clear the MenuItem's Items list prior to building the controls and I verify that the controls hierarchy is structurally as expected after the control construction. Yet when one of my callbacks is called, my MenuItem list magically has some items added to it. None of my other controls appear affected at all. As a hack, I can remove the duplicates manually in my menu's OnMenuItemClick event, but I'd have to do the same in any of the callbacks I receive. Obviously I'd rather prevent this from happening. This has me stumped and I haven't been able to find anything online about it. Why would one set of controls have some content duplicated, yet every other control maintain its state correctly? My code is really simple so there isn't a way to add additional menu items without also adding the views. Anyway, there are a correct number of items prior to clicking on the tab/checkbox, an additional set immediately following in the callback.
This is my first time using ASP.NET, so I'm learning as I go. :) Thanks!
My problem was that I was not testing for postback before creating the controls. The code below is working for me.
In my user control's code behind:
protected void OnInitComplete( EventArgs e )
{
if( !Page.IsPostBack )
{
CreateMyControls();
}
}
I have a view containing a ListView and an "Edit" Button. The ListView's ItemSource is bound to an ObservableCollection<Account> property on the underlying view model. Its SelectedItem property is also bound to the view model.
When the edit button is clicked, the existing view model launches an editing view/view model pair ("editing screen") allowing the user to edit the currently selected Account. The Account to edit is determined by the main view model's SelectedItem property.
Problem: Any changes made in the editing screen are immediately reflected in the other screen's ListView, even before the edit screen's "Save" button is clicked. Why this happens makes sense--Account is raising property change events when its properties are changed and the ListView is processing those notifications.
Desired Outcome: Bound controls (like the ListView) should only see editing screen changes after"Save" is clicked.
Possible Solutions
Suspend Account's property change notifications while editing is underway. Disadvantages: If a manual data-binding update is performed while an Account instance is being edited, the "in-progress" changes will appear on the ListView even though those changes haven't been raising notifications. Also, if the user launches a second edit window for the same Account, they will see the "in-progress" changes. Idea rejected.
Have the editing screen view model wrap the Account instance in some kind of EditingAccount class that copies changes made to it back to the original Account only when Save() is called. Should the editing screen take on the responsibility of facilitating this wrapping or should it ask the service layer to do it?
What do you think of these options? How do you solve this problem when you encounter it?
I would go with some version of the second option. Basically this is a variation of the MVVM pattern which is considered the "right" way to do WPF/Silverlight code. Basically you should have a ModelView object for each "screen" (View) that wraps the model and exposes the model in a format specific to the View so it does exactly what the View needs and NO MORE.