Any example of changing menus and supporting closing for an 'AllActive' tabbed application? - tabcontrol

I'm a CM newbie and trying to get my head around CM. I am building an application where each tab allows the user different functionality for accessing a server where the active work in all tabs (if any is active) could be running async to each other so the shell is an "Conductor.Collection.AllActive" which I hope was the correct choice. I am looking for suggestions or an sample in two areas -
I would like to have the main shell own the application menu and the tab control, and to change the application menuitems depending on the tab selected and then have the menuitem clicks routed to the respective VM for the tab.
Since all tabs could potentially be doing active work simultaneously, I am hoping for an example of how the VM on each tab can participate in helping to decide (via dialogs to the user) if the application can be closed if the close menuitem or the application X icon is clicked. Or if the close should be cancelled per the user response (e.g. they say 'no' since there are unsaved files).
Any examples and suggestions much appreciated.

I created a sample of a possible way to do this. Using a SharedViewModel that contains a collection of MenuItems. The SharedViewModel is injected into the ShellViewModel and each TabViewModel. The Menu control binds to the collection of MenuItems.
When a tab's OnActivate fires the Menu items can be updated by the TabViewModel.
<HierarchicalDataTemplate DataType="{x:Type viewModels:MenuItemViewModel}"
ItemsSource="{Binding Path=MenuItems}">
<ContentControl cal:View.Model="{Binding}" />
</HierarchicalDataTemplate>
<Menu IsMainMenu="True"
ItemsSource="{Binding SharedViewModel.MenuItems}" />
SharedViewModel:
public class SharedViewModel : PropertyChangedBase
{
private List<MenuItemViewModel> _menuItems;
public List<MenuItemViewModel> MenuItems
{
get { return _menuItems; }
set
{
_menuItems = value;
NotifyOfPropertyChange(() => MenuItems);
}
}
}
Example of a TabViewModel updating the Menu:
protected override void OnActivate()
{
base.OnActivate();
SharedViewModel.MenuItems = new List<MenuItemViewModel>
{
new MenuItemViewModel
{
Header = "MainMenuItem1",
MenuItems =
new List<MenuItemViewModel>
{
new MenuItemViewModel {Header = "SubMenuItem1"},
new MenuItemViewModel {Header = "SubMenuItem2"},
}
},
new MenuItemViewModel
{
Header = "MainMenuItem2",
MenuItems =
new List<MenuItemViewModel>
{
new MenuItemViewModel {Header = "SubMenuItem1"},
new MenuItemViewModel {Header = "SubMenuItem2"},
}
}
};
}

Related

UWP Custom ListView to scroll down

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);
}

Eclipse RCP: Can I remove Orphaned Perspectives from the Perspective Bar?

I'm developing an RCP that has two product versions, a core app and one with some extensions. If a user opens the core app after having opened the extended app in the same workspace, eclipse detects a perspective used only in the extended app and makes a local copy of it, so it shows up in the perspective toolbar as an orphaned extension.
I created an activity to hide the extended app perspective when running the core app. That hides it from the perspective menu and the perspective shortcut menu, but it doesn't remove it from the perspective toolbar.I also tried detecting orphaned perspectives from the active page of the active workbench window (by looking for angle brackets in the label) and removing them with PlatformUI.getWorkbench().getPerspectiveRegistry().deletePerspective(perspective), but this doesn't affect the perspective toolbar either. The perspective I'm removing is not present in the core app.
Is there a way I can access the perspective toolbar programmatically so I can remove any orphaned perspectives? Or any other approach tha would work?
I thought a good solution would be creating a custom perspective switcher, but that path was blocked by an eclipse bug. There is a suggested workaround, but it did not work for me. I created a custom perspective switcher toolbar, but I could find no way to make it update when perspectives are opened or activated. My attempts are documented here.
I removed the orphan perspectives in a workspace shutdown hook, but for some reason an NPE is thrown by the E4 workbench (LazyStackRenderer line 238) when I select a perspective in the switcher that was opened but not selected when I launched the app.
I got it to work as desired by closing all open perspectives on shutdown, after storing their IDs in a preference value, and then opening them again when the app is launched in the WorkbenchWindowAdvisor. It's a bit of a hack, but it's the only way I could find to avoid the E4 workbench NPE, which also prevents setting the perspective from the toolbar until it's closed and re-opened from the Window menu.
Here's my code.
...
IWorkbench workbench = ...
static final String PERPSECTIVE_ID_1 = ...
static fnal String PERSPECTIVE_ID_2 = ...
static final String PREFERENCE_KEY = ...
workbench.addWorkbenchListener( new IWorkbenchListener() {
public boolean preShutdown( IWorkbench workbench, boolean forced ) {
IPerspectiveDescriptor[] openPerspectives = page.getOpenPerspectives();
page.closeAllPerspectives(false, false);
StringBuilder sb = new StringBuilder();
String delim = "";
for (IPerspectiveDescriptor persp : openPerspectives) {
if (!persp.getId().equals(PERSPECTIVE_ID_1) && !persp.getId().equals(PERSPECTIVE_ID_2) {
sb.append(delim + persp.getId());
delim = ";";
}
}
getPreferenceStore().setValue(PREF_KEY, sb.toString());
return true;
}
public void postShutdown( IWorkbench workbench ) {
}
});
class MyWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
static final String PRODUCT_ID_1 = ...
static final String PRODUCT_ID_2 = ...
static final String PREFERENCE_KEY = ...
...
#Override
public void postWindowOpen() {
IWorkbenchPage page = getWindowConfigurer().getWindow().getActivePage();
String savedOpenPerspectiveStr = getPreferenceStore().getString(PREFERENCE_KEY);
if (!"".equals(savedOpenPerspectiveStr)) {
List<IPerspectiveDescriptor> openPerspectives = new ArrayList<IPerspectiveDescriptor>();
String[] perspectiveIds = savedOpenPerspectiveStr.split(";");
if (perspectiveIds.length == 0) {
openPerspectives.add(PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(savedOpenPerspectiveStr));
} else {
for (String id : perspectiveIds) {
openPerspectives.add(PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(id));
}
}
//successively setting perspectives causes them to appear in the perspective switcher toolbar
for (IPerspectiveDescriptor persp : openPerspectives) {
page.setPerspective(persp);
}
}
//now we set the appropriate perspective
if (Platform.getProduct().getId().equals(PRODUCT_ID_1)) {
page.setPerspective(PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(PERSPECTIVE_ID_1));
} else if (Platform.getProduct().getId().equals(PRODUCT_ID_2)) {
page.setPerspective(PlatformUI.getWorkbench().getPerspectiveRegistry().findPerspectiveWithId(PERSPECTIVE_ID_2));
}
}
...
}

How can I bind source MediaCapture to CaptureElement using Caliburn.Micro?

On Windows Phone 8.1, I am using the Caliburn.Micro view-model-first approach, but as the view model cannot have any knowledge of the view, I cannot see how I can bind a MediaCapture object to a CaptureElement in the view.
I had the same problem. I'm using MVVM Light with Windows Phone 8.1 WinRT (Universal Apps).
I used ContentControl and binded to CaptureElement:
<ContentControl HorizontalAlignment="Left"
Width="320" Height="140" Content="{Binding CaptureElement}"/>
CaptureElement and MediaCapture are properties in my ViewModel:
private MediaCapture _mediaCapture;
public MediaCapture MediaCapture
{
get
{
if (_mediaCapture == null) _mediaCapture = new MediaCapture();
return _mediaCapture;
}
set
{
Set(() => MediaCapture, ref _mediaCapture, value);
}
}
private CaptureElement _captureElement;
public CaptureElement CaptureElement
{
get
{
if (_captureElement == null) _captureElement = new CaptureElement();
return _captureElement;
}
set
{
Set(() => CaptureElement, ref _captureElement, value);
}
}
And next I call ConfigureMedia() in ViewModel's constructor:
async void ConfigureMedia()
{
await MediaCapture.InitializeAsync();
CaptureElement.Source = MediaCapture;
await MediaCapture.StartPreviewAsync();
}
It's important to firstly initialize MediaCapture, next set Source and finally StartPeview. For me it works :)
If you're trying to keep strict view / view model separation then there are couple of possibilities.
Have you tried straight binding?
<CaptureElement Source="{Binding SomeMediaCapture}" />
If that doesn't work another one is create your own attached property that you could put on CaptureElement. When that property is set you can set the source yourself.
<CaptureElement custom:CaptureHelper.Source="{Binding SomeMediaCapture}" />
Here's a sample of doing some similar with web view and creating an html binding.
The way I tend to do this though is create an interface abstracting the view (say ICaptureView) that the view implements.
I can then cast the view held by the view model
var captureView = (ICaptureView) GetView();
where ICaptureView implements a SetCaptureSource method. This way it's still testable as you can attach a mock ICaptureView to the view model for testing.
Adding to Hawlett's answer, I had to do a little bit more to get the camera displaying correctly. I have changed ConfigureMedia() to be:
private async void ConfigureMedia()
{
_deviceInformationCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
await MediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = _deviceInformationCollection[_deviceInformationCollection.Count - 1].Id
// The rear-facing camera is the last in the list
});
MediaCapture.VideoDeviceController.PrimaryUse = CaptureUse.Photo;
MediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
CaptureElement.Source = MediaCapture;
CaptureElement.Stretch = Stretch.UniformToFill;
await MediaCapture.StartPreviewAsync();
}
I used ContentControl and bound to CaptureElement and It works for me but only the first time. If I navigate to another page and I come back to camera's page I can't see camera preview. I don't call method as StopPreviewAsync() I only navigate to another page.

gwt menu implementation

I want to implement menu in GWT as shown on this website:
http://www.openkm.com/en/
I have created the menu system and I am able to display alerts from menu using following code:
Command cmd = new Command() {
public void execute() {
Window.alert("Menu item have been selected");
}
}
I want to get rid of window.alert() and display my application pages from menu.
Create and load the appropriate page. For example if you use UiBinder then:
MyPage selectedPage = new MyPage(); // creating of your panel
RootPanel.get().clear(); // cleaning of rhe RootPanel
RootPanel.get().add(selectedPage); // adding the panel to the RootPanel
First create an array list of views
public List<UIObject> viewsList = new ArrayList<UIObject>();
Add a view to that list
viewsList.add(addMovieView);
Send the view you want to select to the helper method
public void changeView(UIObject selectedView) {
for(UIObject view : viewsList) {
if(selectedView.equals(view)) {
view.setVisible(true);
} else {
view.setVisible(false);
}
}
}
Are you trying to make the entire page GWT, or just the menu? If it's just the menu, you will need to embed a GWT element into your overall HTML, then call something like
Window.open(linkURL, "_self", "");
from the appropriate menu items, which will navigate to another page.

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();
}
});