Reputation: 563
I have a few public property/objects in my MainWindow (this window is set as my start up object). I want to be able to bind to those properties from a view that show from inside that window.
I can use the following code in my codebehind, and it works.
this.DataContext = ((MainWindow)((App)Application.Current).MainWindow).TippingSourceCollection;
I want to do the same thing with XAML.
Can anyone show me how?
Thank you John
Upvotes: 1
Views: 2005
Reputation: 69979
If you have set the Window's DataContext
to the MainWindow
object, surely you can just bind to its properties as normal... therefore, try this in your Window's code behind:
DataContext = (MainWindow)((App)Application.Current).MainWindow;
Then in your window's XAML, just do something like this:
<ListBox ItemsSource="{Binding TippingSourceCollection}" ... />
EDIT >>>
Ok, so you want to do it the 'MVVM' way. One solution would be to put your MainWindow
properties into a base view model class that all view models have access to. For example:
public class BaseViewModel { // declare your MainWindow properties here }
public class OtherViewModels : BaseViewModel { // specific properties here }
In this way, all of your view models will have access to all of the properties declared in the base view model. But then... all of your view models will have access to these properties, and have their memory footprint enlarged by them accordingly.
Therefore, I'd like to point out that MVVM has no rule that says that you should not use the code behind files for such setup code. The main reason to use MVVM is to provide the Separation of Concerns between the UI and the business logic that enables us to test them separately. As such, it is recommended that you do not put any business logic into your code behind files, however setting UI properties like this is not a problem at all.
Upvotes: 0
Reputation: 670
You can try something like this. But it your methodology and trying to implement/learn MVVM may be a bit flawed having this collection on the main window, rather than in a static class that the viewmodel of the control can access when it is created.
<UserControl DataContext="{Binding TippingSourceCollection, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" />
Upvotes: 0
Reputation: 35679
technically it can be achieved via binding with static Source
DataContext = "{Binding Source={x:Static Application.Current},
Path=MainWindow.TippingSourceCollection}"
but I would suggest to create specialized ViewModel class/classes for your Views
Upvotes: 2