Reputation: 769
In my current scenario (WPF, MVVM), I have a user control which hosts a visio diagram. This user control is located on a view, next to a number of labels and a datagrid element.
The user control contains a DependencyProperty object SelectedNode
which value is updated with the information received from the Visio diagram. The labels' content are binded so that they display the information contained in the SelectedNode
(e.g. id, name):
<Label Grid.Row="1" Grid.Column="1" x:Name="lbNodeIdValue" HorizontalAlignment="Left"
Content="{Binding ElementName=visioControlUC, Path=SelectedNode.Id, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"/>
Every time I change the selection in the diagram, the label's content changes as expected.
Next to this label, I would like to display a datagrid containing information based on the id displayed in the label. This is where I ran into problems, as I can't seem to be able to get the value of the Content
property of the label in the viewmodel class.
I have tried using the MultiBinding
property on the Content
element of the label, and creating a second binding with Mode=OneWayToSource
to set the value of the label's Content
to a property I have defined in the viewmodel class.
What would be a proper way to retrieve this value in my viewmodel class?
Thanks, Adrian
Upvotes: 0
Views: 89
Reputation: 132548
Ideally your Datagrid's ViewModel
should get the value of the selected label from the other ViewModel
. You should not rely on Views
to transfer application data between ViewModels
.
It sounds like the SelectedNode
value originates from the UserControl
, and not the ViewModel
, so you'll need to bind the UserControl.SelectedNodeId
to a ViewModel
somewhere so the ViewModels have access to this data
<local:myUserControl x:Name="visioControlUC"
SelectedNode="{Binding SelectedNodeId}" />
If the value is needed by more than one ViewModel
, I would highly recommend some kind of event system, such as MVVM Light's Messenger
or Prism's EventAggregator
. This would allow your ViewModels
to subscribe to something like a SelectedNodeChangedEventMessage
, and the ViewModel
which actually contains the SelectedNodeId
can broadcast that message anytime the value changes. You can find an example of both on my blog post about Communication between ViewModels.
Upvotes: 1