Reputation: 1
My question if very similar to question "Exposing DataGrid SelectedItem in parent UserControl in WPF" which is here in this forum. I have an XAML file which has two UserControls being used a a master-detail window. The first UserControl is just a DataGrid which holds some widgets and the second one holds the detail information of the selected widget. I am trying to user the MVVM pattern so I am trying to avoid using a RoutedEventHandler to handle the SelectionChanged event of the DataGrid. I created a RoutedEventHandler to test if my Detail-info UserControl would be populated with the selectedItem from the DataGrid and it did. So I proved that it worked.
Now, after removing the RoutedEventHandler and proceeding to use a SelectedItem Dependency Property to let the UserControl which displays the detail info nothing gets display on this UserControl when the DataGrid selection changes. My View needs to be aware of the changes. I read Josh Smith's article in which he provides an example using a listview. I have read quite a few posts/blogs but most of them do not provide an answer or do not user the DataGrid in a UserControl.
In my view I set the DataContext of my window to the windowViewModel which returns a Collection of widgetViewModel and I also set the DataConext of a groupbox on the same window which holds the Detail widget info to the windowViewModel.SelectedItem dependency property.
here is the main code
<UserControl.Resources>
<Style x:Key="WidgetItemStyle" TargetType="{x:Type toolkit:DataGridRow}">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</UserControl.Resources>
<Grid>
<toolkit:DataGrid
x:Name="dgWidgets"
DataContext="{StaticResource WidgetsList}"
ItemsSource="{Binding}"
SelectedItem="{Binding ElementName=WidgetsUserControl, Path=SelectedItem, Mode=TwoWay}"
SelectionUnit="FullRow"
SelectionChanged="dgWidgets_SelectionChanged"
IsSynchronizedWithCurrentItem="true"
ItemContainerStyle="{StaticResource WidgetItemStyle}"
>
<toolkit:DataGrid.Columns>
.... column defs
In the window which contains the two UserControls I have:
var viewModel //this variable holds the windowViewModel
this.DataContext = viewModel;
this.gBox.DataContext = viewModel.SelectedItem;
I have been struggling with this for quite some time and still do not know the problem is.
Upvotes: 0
Views: 1057
Reputation: 2002
You are right there. I got this to work simply by binding the SelectedItem to a property "currentWidget" on my VM. When the value is changed, you know the user selected a new record in the master grid. Bind your detail control to the same property (if it contains all the details you need) and you are home.
XAML
SelectedItem="{Binding currentWidget, Mode=TwoWay}"...
VM Code
private Widget _currentWidget;
public Widget currentWidget
{
get { return _currentWidget; }
set
{
_currentWidget = value;
NotifyPropertyChanged("currentWidget");
}
}
Upvotes: 2