WPF MVVM Controls incorrectly sharing ViewModel - wpf

I have a control:
DailyHours. That has a collection of custom TimeEdit controls I created. Each control is supposed to bind to the DailyHours view-model class. Instead it tries to find the values I bind to in the TimeEdit control.
An example of a TimeEdit control binding:
<bc:TimeEdit Time="{Binding CurrentOperatingHours.MondayClose}" ></bc:TimeEdit>
The TimeEdit control has its own internal values for hour and minute that are bound to Hour and Minute properties. For this reason the DataContext for the TimeEdit control is itself.
public TimeEdit()
{
InitializeComponent();
this.DataContext = this;
}
However this causes the DailyHours control to incorrectly bind the time value. It looks for the CurrentOperatingHours property in the TimeEdit control instead of its own view-model.
How do I get my TimeEdit control to bind correctly with internal values without disturbing binding on its parent container?

you can go two ways: remove this.Datacontext = this; from your usercontrol and use bindings with ElementName for Hour and Minute (good practise!) or use relativeSourceBinding in your Mainview (bad practise).
i answered a similar question here.
ps: an usercontrol should never set the datacontext to it self. this brokes datacontext inheritance and its not an expected behavior.

try this
Time="{Binding DataContext.CurrentOperatingHours.MondayClose, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}">
I hope this will work .

Related

Binding a control when the View is bound to a ViewModel?

Here is my situation. I have a View and a ViewModel. The view's DataContext is set to the ViewModel. Due to the use of a 3rd party control, I am forced to put some code in the code-behind. In the code-behind I create an object called StraightConnectorTool.
In my View, I need to bind to this object. If the View's DataContext is set in the code-behind:
DataContext = this;
The following binding works fine.
<BarItemToolBehavior ActiveTool="{Binding ActiveTool, ElementName=diagram, Mode=TwoWay}"
Tool="{Binding StraightConnectorTool}"/>
Where diagram is the name of the 3rd party control on the View and ActiveTool is one of it's properties.
However, if the View's DataContext is set to the ViewModel, the binding doesn't work. I'm stuck trying to figure out how to bind to the view when it's DataContext is set to the ViewModel. Any ideas?
It's not good practice, but you can bind the BarItemToolBehavior's DataContext to the view. Either by name in the code behind or in XAML using RelativeSource FindAncestor to find the view. A better solution would be to move that object to the VM where it belongs.

trying to bind datagrid item source to a property in another class

I have a WPF app with a MainWindow. The MainWindow consists of several CLR properties of type ObservableCollection. The MainWindow has a datagrid, whose ItemsSource property is bound to one of the observable collections (works fine). Next, I have a dialog. Its purpose is to display one of the observable collections from the main window in a datagrid. The dialog gets instantiated in the MainWindow. Initially I was passing the ObservableCollection to the dialog's constructor, and copying it into the dialog's CLR property. Then I would set the DataContext of the dialog to itself, and bind the ItemsSource property in the datagrid to the name of the CLR property. This worked fine.
Is there a better way to do this instead of passing the observable collection through the constructor? I tried setting the ItemsSource property of the Datagrid in the dialog to the observable collection in the MainWindow by using the GUI editor, which generated a binding using RelativeAncestor, but the data did not show. The problem is I have a bunch of dialogs that are meant to display data from the MainWindow, and I feel like there should be a simpler solution rather than passing everything to dialog's constructor. Also, would the dialogs be considered SubViews? The main window is a view.
Let's say your Dialog control is named DialogControl and has a DependencyProperty named Items defined in its code behind. In the XAML, I would bind this property to the DataGrid like this:
<DataGrid ItemsSource="{Binding Items, RelativeSource={RelativeSource Mode=
FindAncestor, AncestorType={x:Type DialogControl}}" />
This RelativeSource binding will go off and search through the properties of your DialogControl class and find the Items property. Note: Do NOT set the DataContext of the UserControl to itself.
Now in your MainWindow.xaml.cs file where you instantiate your DialogControl, you can set the Items property:
DialogControl dialogControl = new DialogControl();
dialogControl.Items = someCollection;
dialogControl.Show();
UPDATE >>>
Oh I see what you're after now... you want to bind from your UserControl to the actual collection in the MainWindow.xaml.cs file. You can still follow my advice, but instead of having the DependencyProperty in your DialogControl, you need to have it in your MainWindow.xaml.cs file. In that case, your binding in the UserControl would be:
<DataGrid ItemsSource="{Binding Items, RelativeSource={RelativeSource Mode=
FindAncestor, AncestorType={x:Type MainWindow}}" />
For this to work, the Items property must be a DependencyProperty.

How do i access a combobox text in a usercontrol from the wpf forms viewmodel?

I have a UserControl with 4 combobox bound to collections in viewmodel for that usercontrol.
I have used this control in a wpf form. This wpf form has its own viewmodel.
How do i access the text from the 4 comboboxes within the wpf form's viewmodel?
EDIT: i saw that you have different viewmodels. now it depends of the use of your usercontrol and the use of mvvm:)
you can use messenger or eventaggregator to comunicate the seleteditems from usercontrolviewmodel to mainviewmodel.
you can also use RelativeSource binding in your usercontrol to bind the selecteditem to your mainviewmodel directly (usercontrol then is just a composition of controls).
you can can rid of the usercontrol viewmodel and put all in the mainviewmodel and take my old example
you can create DependencyProperties for the SelectedItems in your usercontrol!(not usercontrol viewmodel!) and bind these to the properties in your mainviewmodel. i think thats the cleanest way if the usercontrol should be a real usercontrol.
old example:
in your viewmodel: //the real code should of course implement INotifyPropertyChanged and raise it properly
public ObservableCollection<string> MyFirstCollection {get; set;}//init once, add,remove,clear to alter
public string MySelectedCombobox1Value {get;set;}
in your usercontrol:
<ComboBox ItemsSource="{MyFirstCollection }" SelectedItem="{Binding MySelectedCombobox1Value, Mode=TwoWay}" />
thats all relating to your question. be sure that you set the DataContext right. you can check this with tools like snoop. the code i posted expected that the dataconext for the combobox is the viewmodel.
The UserControl should inherit the data context of the form you're adding it to which would be the view model. Any bindings in the UserControl would then be relative to the inherited data context. Have you tried binding to a view model property to ComboBox.Text?
UPDATE
Sorry, misread your question. Didn't see that the user control already has its own view model.
While it seems like there's a better approach, you could expose dependency properties on the user control that exposé the text of each combobox. Just thinking out loud.
The only clean way to do this is with binding, and the only way that would be recommended is if the user control exposes a DependencyProperty for the ViewModel or the individual text properties (as was suggested by sellmeadog) for consumption. Then you can have a property in the parent ViewModel that binds directly to that Dependency Property.

Binding a combobox in XAML to a childwindow property

I want to display a child window that contains a combobox with several values coming from one of the child window's property:
public partial class MyChildWindow : ChildWindow
{
private ObservableCollection<MyClass> _collectionToBind = // initialize and add items to collection to make sure it s not empty...
public ObservableCollection<MyClass> CollectionToBind
{
get { return _collectionToBind; }
set { _collectionToBind = value; }
}
}
How do I bind in XAML my combobox to the ComboBoxContent collection (both are in the same class)? I've tried several things such as:
<ComboBox x:Name="linkCombo" ItemsSource="{Binding Path=CollectionToBind }" DisplayMemberPath="Description">
I've only been able to bind it in the code behind file and would like to learn the XAML way to do it.
Thank you!
In this case I would use ElementToElement binding like this:-
<ComboBox x:Name="linkCombo" ItemsSource="{Binding Path=Parent.CollectionToBind, ElementName=LayoutRoot }" DisplayMemberPath="Description">
You give the Content element of the ChildWindow the x:Name of LayoutRoot (in the standard template for child window this is done for you). Hence you can bind to this named element and navigate to the containing ChildWindow by using its Parent property.
Using DataContext = this is tempting and works in simple scenarios but things can get awkward in more complex requirements when the DataContext has already been taken in this way.
You need to set the DataContext of the ChildWindow to what contains the values you'd like to bind to. In this case where you're putting the values you want to bind to on the ChildWindow itself so just put a line in the constructor assigned the DataContext to itself.
DataContext = this;
You can also do this using a RelativeSource binding in the XAML, like this:
{Binding Path=CollectionToBind, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}
However, a better way to do this would be to put the CollectionToBind in a separate class and assign it to the Window DataContext. Now both the Window and the XAML Bindings can all refer to the same class as the DataContext and you can isolate more of your logic into this class rather than putting it in the Window implementation.

WPF access info from the containing Control

I have a UserControl(a) with a stackpanel which has its ItemSource set to a collection.
The StackPanel then contains a set of UserControl(b) that contain a few buttons and a datagrid control.
Is there a way from the code behind in the UserControl(b) to access properties in the code behind of the parent UserControl(a).
Basically when UserControl(a) loaded into a window a parameter is passed in that contains whether the form will be considered read only or not. I would like bind the visibility of the buttons in Usercontrol(b) to the readonly property in the codebehind of the parent UserControl(a).
Normally with WPF I'd suggest you implement the Model-View-ViewModel pattern (see MSDN).
With this pattern you'd create a ViewModel with all of the data in that you want to bind. This would be set as the data context for the (a) usercontrol. That control would then bind all of it's controls to properties on the datacontext.
The child (b) usercontrol would inherit this datacontext and could therefore bind it's controls to the same properties as (a) uses. This is because datacontexts are inherited down the logical (and visual) tree until such point as it's overridden.
So for you I'd be looking at creating a ViewModel that contains the property ReadOnly. You can then set this ViewModel object as the datacontext for the (a) usercontrol. The (b) usercontrol, since it's under the (a) usercontrol hierarchy will inherit the same datacontext. This will then allow you to bind controls within (b) to the same properties as (a) as shown below.
<Button IsEnabled="{Binding ReadOnly}"
Context="Click me!"
Command="{Binding ClickMeCommand}" />
To set the datacontext in the view code-behind I do something like this constructor shown below.
public MyView(IMyViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
MyView is the class that inherits from UserControl in your instance. You don't have to get the viewmodel in the way I have, I'm using Unity to inject the viewmodel into the views that are constructed automatically since I'm using Prism but you can just create it as a normal object and assign it to the datacontext.
Note that I've also bound the command to the button using the datacontext as I usually expose those via the ViewModel too, this is easy if you create a wrapper class that implements ICommand and proxies to a delegate. See DelegateCommand blog article or look at the DelegateCommand class in Prism if you are interested.
If for some reason you do override the datacontext, which can happen when using a master/details view where you change the datacontext of the details section of the view to be the currently selected item in the list, then you can still access the parent datacontext by using a relative source binding.
E.g.
<ComboBox Grid.Row="1" Grid.Column="1" x:Name="Unit" IsReadOnly="True"
ItemsSource="{Binding Path=DataContext.AvailableUnits, RelativeSource=
{RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}}}"
DisplayMemberPath="Name" SelectedItem="{Binding Unit}" />
Note the ItemsSource binding uses a relative source to find the parent window and then bind to a property of it's datacontext. I've also split the ItemsSource binding within the quotes across multiple lines for clarity here but don't do that in your xaml, I'm not sure it'll work there (not tried to see if markup extensions are that tolerant of whitespace).

Resources