WPF Binding Between Controls - wpf

I have a control on a page that contains a listbox. I also have another control which is a detail view.
Both of the controls have their own ViewModel which their child controls bind to.
Image Outlook. It has a list of folders and when you select a folder the detail control displays the contents of the folder.
How can I bind the detail control to the selected item in the list control?

If I got it correctly, you have master-detail situation. Can you add list of details ViewModel as property of master ViewModel? That way you don't need anything special. It should work automatically. Something like this:
public class MyMasterViewModel
{
public List<MyDetailViewModel> Details
{ get; set; }
}
Set collection of MyMasterViewModel as DataContext to both views and configure binding appropriately. As you move through master list, detail list will be automatically updated.
You'll probably need to set IsSynchronizedWithCurrentItem property:
<ListBox ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True"
DisplayMemberPath="Something"/>

Use element-to-element binding, here as link to MSDN page http://msdn.microsoft.com/en-us/library/ms752347.aspx with master-detail example.

Related

MVVM - Menu View with Preview View (Shared ViewModel) approach

I've just started my journey with MVVM and WPF and I need an advice to solve my problem or rather guide me towards right solution.
Link to image: https://s12.postimg.org/md0h6fv3x/Simple_App.png
Description (what I want to achieve):
View A is a menu (UserControl) with ListBox and DataContext: V.ObservableCollection
View B is a preview to selected item from View A ListBox
View A & B are loaded from MainWindow
What is simpliest and cleanest approach to achieve that?
I was thinking about sharing the same ViewModel with View A&B.
Create a SelectedItem property in ViewModel and then put it MainWindow's resources and bind datacontext to View A & B
Is it valid approach? Will that VM be updated properly in both views if it get changed?
Somehow bind View's A listbox SelectedItem to View B preview mode but don't know how.
Use only one ViewModel.
Eg; Pseudo code :
public class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<Employee>{get;}
/* provide change notification in ChosenItem */
public Employee ChosenItem{get;set;}
}
Use this ViewModel as DataContext for both Views.

How to bind to a method on ViewModel with data from View

I currently have one view with 3 fairly simplistic view models. For the sake of this discussion, we will focus on 2 of the three view models.
The View is a User Management user control. It contains a DataGrid that has its ItemsSource binding set to a UserListViewModel. This view model simply displays user information in the data grid.
The User Management View also contains some other controls, such as buttons for adding new users and removing users. Those buttons are currently bound to a second view model called UserManagementViewModel. For example, the Remove button will successfully call the RemoveUser method on the UserManagementViewModel.
My question is, via XAML (as I hate code-behind), how can I pass the SelectedItem property of the DataGrid (bound to UserListViewModel) into the RemoveUser method call on the UserManagementViewModel? I realize that, in the MVVM design pattern, my view model can't look into the view to retrieve the information necessary, so there must be a way via binding to pass that information into the method.
XAML code examples (or links that show how) to perform similar functionality would be appreciated. Thanks for any help!
you can simply use a commandparameter
<Button Command="{Binding RemoveCommand} CommandParameter="{Binding Elementname=gridUser, Path=SelectedItem}" />
or your UserManagementViewModel have access to the UserListViewModel then you need a command without commandparameter and simply use the SelectedUser property of your UserListViewModel instance
public void ExecuteRemove()
{
var userToRemove = this._myUserListViewModelinstance.SelectedUser;
...
}
I believe what you seek is commanding with a command target bound to the datagrid's selecteditem where one can route such information from the datagrid; say when a button is pressed.
See Commanding Overview on MSDN

How can I easily expose bindable properties of nested controls from a custom UserControl?

My first question here on the Stack. Forgive me for the bad explanation in advance.
I am working on my first MVVM application (Silverlight). I have a custom user control that contains a ListBox to show navigation items. This control is placed in my main xaml page. I don't know if I need to create a composite view model (my main page view model) with a view model especially for the custom control in it or if there is some way to elevate the ListBox properties that I need to bind to.
Through XAML I don't know how to bind, let's say, the ItemsSource property of the ListBox inside the custom control to my main page viewmodel. Basically, I'm at the point that I am questioning my design decision for trying to bind the custom control through my main page view model.
What I have done so far is create dependency properties for the custom control and try to tunnel those dependency properties down to the ListBox properties. I've achieved success with this method for ItemsSource but am having issues with SelectedItem.
Even if I do get SelectedItem to work, it still feels Wrong. Thanks for any advice in advance.
The UserControl should inherit the DataContext from its parent control, unless you are setting it directly. You can then bind to the properties on your view model from your UserControl.
If you would like to create a ViewModel specifically for the UserControl, you can also do that. You would then expose it as a property on your main ViewModel, and bind to it in the MainPage. Example:
public class MainViewModel
{
public ChildViewModel ChildInfo { get; private set; }
}
And then in the view:
<Grid>
...
<lcl:ChildView DataContext="{Binding ChildInfo}" />
...
</Grid>
Your ChildViewModel would then contain properties like SelectedItem to bind your ListBox to.

How do I databind to a ViewModel in Expression Blend?

In WPF and Silverlight you can make a view model object and set it into the DataContext of a control when the control is constructed at runtime. You can then bind properties of the visual object to properties in your DataContext.
One way to set the binding is to type the binding directly into the tag:
<TextBox Text="{Binding Path=Description}"/>
And this will bind the textbox to the Description property in the view model.
The problem with typing in the binding is that you may make a typing mistake. (And you will almost certainly make a mistake if you have hundreds of bindings to make.)
In Expression Blend there is a little white dot beside the Text property in the Properties window. This brings up a menu from which you can Create Data Binding.
How can I get my view model properties to show in the Create Data Binding dialog so that I can select them.
Will the configuration of data binding in Blend interfere with setting my view model into the DataContext at runtime?
One technique is to include the VM as a resource in your view:
<UserControl>
<UserControl.Resources>
<local:YourViewModel x:Key="ViewModel"/>
</UserControl.Resources>
</UserControl>
You can then reference that as DataContext="{StaticResource ViewModel}" elsewhere.
Can't say I like it, but I can't say I like any of the view-first idiosynchrasies that Blend imposes on your design.
I experimented with Blend to find the drag and drop approach to data binding which still lets you override your view model in code easily.
First make your view model object which implements INotifyPropertyChanged and raises the notify event in the setters. The view models can be hierarchical. For example you could have an ObservableCollection within your main view model.
In Blend open up your page or control and go to the data tab.
On the right open the menu under the "Add live data source" icon.
Pick "Define new object data source"
Select your top level view model class and confirm the dialog
In my experiments I found that it was important to bind the data source to where I wanted it first or else Blend might make a less than optimal configuration if I didn't do the next step first.
Open the Objects and Timeline window in Blend
Select the root object, for example UserControl
Open Properties and verify that the root object is selected
Find DataContext and click the square to open the menu and select DataBinding
Select the data source that was just previously created
Now that the data source has been created data binding is very easy.
put some controls on the page
open the Data window
from the DataSource for your view model drag properties onto the controls to create the bindings or set the binding from the Properties window.
Now you can create you live view model object in the constructor of the control
public MainPage()
{
// Required to initialize variables
InitializeComponent();
mVm = new MyViewModel();
this.DataContext = mVm;
}
private MyViewModel mVm;
Add any initialization to retrieve data and you are ready to go.
I have a screen cast on my blog Blendable MVVM : Introduction and Databinding which shows setting this up for Siverlight.
Essentially you create the ViewModel as the DataContext of the UserControl using the "New Object Initialiser" and then using the "Explicit Data Context" tab of the Binding dialog for the controls themselves.
Hope this helps.

How do I pass a specific viewmodel object in a button's CommandParam?

I have a simple WPF program using the Master-Detail UI pattern, where the Detail shows the currently selected item of a collection in the Master pane. I'm using MVVM, and each XAML page is backed by a ViewModel object which is set as it's DataContext.
Now, I want to add a DELETE button in the Master pane to delete from the master list of items. However, I can't figure out how to pass the viewmodel object of the currently selected item as a button CommandParameter to the routed command handler code.
Thanks in advance for any pointers.
Mike
Something similiar to what Paul has shown is where your view model will know which item is currently selected. I.e.
public class MyVM
{
public ObservableCollection<MyObject> MyCollection { get; set; }
public MyObject CurrentItem { get; set; }
}
Your XAML can then be simply
CommandParameter="{Binding Path=CurrentItem}"
As long as your master pane sets the CurrentItem property when you select it, your command can simple have the CurrentItem set as the command parameter.
One option would be to create each command with a reference to the view model, and create a property on the view model which is bound to the currently selected item. This way you don't need to pass the selected item as a parameter - the command can retrieve it from the VM. If this isn't suitable for your circumstances, you could pass the selected item something like this:
<Button Content="Delete"
Command="{Binding DeleteCommand}"
CommandParameter="{Binding ElementName=listBox_, Path=SelectedValue}" />
Where listBox_ is a control which derives from Selector.
Hope that helps,
Paul

Resources