Usercontrol with treeview selected event that refreshed another usercontrol not working - wpf

I'm relatively new to WPF programming and can't seem to get this working correctly. This is in my mind something rather simplistic that i would like to get working so I didn't try the MVVM framework and decided to keep it simple.
I have a usercontrol treeview with report paths. I have another usercontrol with a reportviewer. Selecting a report path in the treeview should refresh the reportviewer.
I can "call" the method from the treeview usercontrol for refreshing the reportviewer in the report usercontrol but nothing happens.
I was reading other posts and some seem to suggest a button event to a delegate that will allow the other usercontrol method to be executed. I'm not using a button event so I'm a bit puzzled.
I thought I could do something like this:
private void treeViewMenu_Selected(object sender, RoutedEventArgs e)
{
//Get the selected item
....
//Call the method of another user control
ReportUserControl ruc = new ReportUserControl();
ruc.RefreshReport();
}
Obviously that didn't work...I know that it shouldn't be too difficult but i am in a brain freeze moment and can't seem to get it working.
Any suggestions would be greatly appreciated.
Thanks!

Related

WPF & MVVM, right way to do it

So I am doing my first WPF MVVM app. Just learning the right principle of MVVM, but there are some things that I don't understand ...
I already have several user controls defined.
First question is what is better to use, UserControl or DataTemplates to change content of the MainWindow?
And how to make "Binding" in the "MainWindow.xaml" to change UserControl/DataTemplates when button is pressed?
For example, When "next" button is pressed then contents of main window disappear and content of user control comes on the screen of "MainWindow.xaml".
Maybe with "" binding, to disable it and enable it?
I found some example which function on DataTemplate A Simple MVVM Example. It helped me to implement some things, but I see some discussions over "UserControl" vs. "DataTemplate" and how to do it? So now I am confused :)
I recently made a WPF application with the MVVM pattern, and I did the following:
I have one 'Window', the mainwindow, and in this window all UserControls are loaded.
Every UserControl has a different Viewmodel, for examples a "GeneralSettingsUserControl" has a GeneralSettingsViewModel for validation and databinding.
Every UserControl has its own codebehind where data is bound to its ViewModel
The following code I found on the internet (I don't know the url anymore) but for me it did the trick to change de ContentControl in the mainwindow.
Switcher.cs:
public static mainWindow mainWindow;
public static void switchPage(UserControl p_objNewPage)
{
mainWindow.navigate(p_objNewPage);
}
mainWindow.xaml.cs
public void navigate(UserControl nextPage)
{
PageContent.Children.Clear();
PageContent.Children.Add(nextPage);
PageContent.LastChildFill = true;
}
PageContent is the name of the Grid where the main content is located. In every UserControl you can call the Switcher.switchPage(new UserControl) to change the content of the window. So when you click a button you can call this method.
Hope it helps and good luck.

Setting DataContext in Catel with WPF

So I've started looking at the Catel MVVM framework and it looks like it will solve a couple of problems I have encountered, but I have one really silly issue. I think I'm just missing something small.
I took one of my smaller WPF projects to switch over the Catel as a way for me to learn it. I have a simple 'Player Registration' form, with fields like name and surname. I recreated my original view model by using the vm codesnippet and all is good, all the properties and attributes I've set up as I've read in the documentation.
I then changed the UserControl I used for 'Player Registration' (PlayerRegistrationView) to a catel:UserControl. I placed PlayerRegistrationView on a standard WPF Window (nothing else, just a xmlns for the View and the view as the only content on the window, no attributes)
But here is my problem:
I have a MainWindow with a button on to open the Window for the player registration. The on-click event simply is this:
private void ButtonPlayerClick(object sender, RoutedEventArgs e)
{
var playerRegistration = new PlayerRegistrationDialog
{
Owner = this,
DataContext = new PlayerRegistrationViewModel(),
};
playerRegistration.Show();
}
Running my program and then clicking on the button results in an NotSupportedException on my PlayerRegistrationView: The view model of the view could not be resolved. Use either the GetViewModelType() method or IViewModelLocator
I tried making the ViewModel a static resource on the window and setting the datacontext there, but it produces the same error.
I am at a loss. What have I missed?
Thanks
The whole point of Catel is that it automatically wires up all the views and view models. The "complex" thing that you are trying to achieve is that you have a view which is placed on a window. You want the window to have the same data context as the view in order to do some stuff in the window as well.
In Catel, it is possible to place any view with datacontext management on a DataWindow (window in Catel). Then it will work like this:
DataWindow
|=> View
If the DataWindow and the View share the same view model type, then they share the same view model. For example:
PlayerRegistrationWindow => derives from catel:DataWindow
PlayerRegistrationView => derives from catel:UserControl
Since both start with PlayerRegistration, they will both be resolved to PlayerRegistrationViewModel automatically.
To show the window, the only thing you have to do is this:
var viewModel = new PlayerRegistrationViewModel();
var uiVisualizerService = ServiceLocator.Default.ResolveType<IUIVisualizerService>();
uiVisualizerService.Show(viewModel);
All will work automatically and you don't have to worry about setting any datacontext yourself.

UI freezed instead of showing BusyIndicator in Silverlight

This is a side-related question to this other question:
BackgroundWorker in Silverlight ViewModel
I have a TabControl where I load many TabItems when the user selects menu options. I load this Tabs by binding the TabControl ItemsSource to an ObservableCollection. When I add a new TabItem to this Collection, it is shown perfectly.
The problem is I've realized that since user press a button until the tab is created (ViewModel and View creation takes a couple of seconds), the screen is freezed.
I've tried to set "IsBusy" before calling the "loadTab" but it doesn't shows up... I've tried almost everything with async calls but the UI thread is in use and it throws an exception when I create the new tab control.
Is there any trick I'm loosing??? Any ideas??? Thanks in advance.
have you seen this post?
http://www.dotnetspark.com/kb/3524-doesnt-your-girlfriend-deserves-more-time.aspx
It helps when you avoid heavy stuff in the load event and make Visible=true after you finish to load all your resources, so in that sense you avoid the user feeling tempted to click something that is not ready yet.
Not sure if it helps, but how about this idea?
public void DoStuff(Object values)
{
//your values object could be anything,
//they might even be some objects from your form
//as long as you dont modify them in the other thread
imgLoading.Visible=true;
var client = new Proxy();
client.OnWorkCompletedAsync +=client_OnCompleted() ;
client.Work(values);
}
void client_OnCompletedAsync(object sender, EventArgs e)
{
imgLoading.Visible=false;
//now you can update the UI with other stuff
}

WPF routed events handling in UserControl

I have a WPF UserControl that contains a button. I also have a WPF Window that contains a button.
In both the UserControl and the Window I place the following line in XAML:
UIElement.PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown"
and in 'OnPreviewMouseLeftButtonDown' I've place a debug print that displays args.Source.
When I click on the button that is inside the window, I get the button as the EventArgs source. However, when I click the button that inside the UserControl (which is also inside a window, so I could test it, but not the same window) I get the UserControl as the EventArgs source.
I tired to see if there is some decorator around the UserControl (using snoop) but it seems straight forward.
I can't understand what is so special about UserControl in WPF that I don't get the right sender. Can someone please explain to me what am I missing?
While the question is old, I recently ran into a similar problem myself, involving the ContextMenuOpening event. Some amount of searching yielded the source code to UserControl here, which contains the following section:
// Set the EventArgs' source to be this UserControl
internal override void AdjustBranchSource(RoutedEventArgs e)
{
e.Source=this;
}
So, apparently UserControl sets the Source of ANY routed event to itself. I have no idea why it does this, though...
Use e.OriginalSource as mentioned above. If you need to find the button, then you can use VisualTreeHelper.GetParent to find the actual Button control.

SL4: need to register for a move (or redraw) event on an Item in an ItemsControl

Not finding a move event or redraw event in the FrameworkElement class. And Google not helping either. So...
I have a custom ItemsControl populated by an observable collection in the VM. The ItemsControl itself leverages the
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
behavior so the user can drag around the whole assembly.
When the user moves the assembly, I want to be notified by each item as the item is repositioned as a result of the assembly moving. So far I have tried registering for
this.myItem.LayoutUpdated += this.OnSomethingNeedsToUpdate;
but it doesn't seem to fire as I drag the assembly around.
Also
this.myItem.MouseMove += this.OnSomethingNeedsToUpdate;
only works if I mouse into the item which is not good enough. Because I am moving the ItemsControl and then have to go mouse into the item to get the event to fire.
Any ideas? Can I look to some ancestor in the visual tree for help in the form of a OneOfMyDecendantsWasRedrawn event or similar? Again I am trying to be notified when an item moves not be notified when the assembly moves.
I would say your best bet would be to add the MouseDragElementBehavior to your custom ItemsControl in code instead of in the Xaml. Here is how this might look (using a Grid since that is easier to demo):
public class DraggableGrid : Grid
{
public DraggableGrid()
{
Loaded += new RoutedEventHandler(DraggableGrid_Loaded);
}
void DraggableGrid_Loaded(object sender, RoutedEventArgs e)
{
MouseDragElementBehavior dragable = new MouseDragElementBehavior();
Interaction.GetBehaviors(this).Add(dragable);
dragable.Dragging += new MouseEventHandler(dragable_Dragging);
}
void dragable_Dragging(object sender, MouseEventArgs e)
{
// Custom Code Here
}
}
In the section that says Custom Code Here you would loop through you Items and notify them that they are being dragged.
I ended up writting another behavior for the individual items I care about and then wrote a LINQ query to search up the visual tree looking for ancestors with the MouseDragElementBehavior attached to them. That query found the ItemsControl since it was an eventual parent of the Item. I was then able to register for the Dragging event as desried.
Thanks again to Bryant for providing the solution over here.

Resources