From mainWIndow.xaml, which uses as DataContext the mainWindowViewModel, I opening a new window with name addNewItem.xaml, which uses as DataContext the ItemsViewModel.
In addNewItem.xaml I have a DataGrid
<DataGrid SelectedItem="{Binding Path=SelectedHotel}" ItemsSource="{Binding HotelsList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Width="350" Header="Hotel" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding Path=Name}"></Label>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
I want to pass the SelectedHotel from ItemsViewModel to mainWindowViewModel.
I tried to do this with the following code (with no luck)
//This is a property from ItemsViewModel
private Hotel _selectedHotel { get; set; }
public Hotel SelectedHotel {
get { return _selectedHotel; }
set {
_selectedHotel = value;
RaisePropertyChanged("SelectedHotel");
OnSelectedItemChanged();
}
}
void OnSelectedItemChanged() {
MainWIndowViewModel = new MainWIndowViewModel(this.SelectedHotel);
}
In mainWIndowViewModel I have also one more Property (with same name, SelectedHotel) which it gets value through the constructor
public MainWIndowViewModel(Hotel selectedHotel)
: this(new ModalDialogService()) {
this.SelectedHotel = selectedHotel;
}
In mainWindow.xaml I want to display a value of the property
<Label Content="{Binding SelectedHotel.Name}" DockPanel.Dock="Top"></Label>
what am I doing wrong?
In general, I need to know the rule of doing something like this.
How could I notify a property from another property?
Thanks
Solution
I solve it with messages from mvvm light.
Finally I found a solution and this comes from mediator pattern. I use the mvvmLight.
From mainWindowViewModel, I registered a message (I don't know if the term of message is the correct one)
public MainWIndowViewModel(IDialogService dialog) {
this._dialog = dialog;
Messenger.Default.Register<NotificationMessage<Hotel>>(this, NotificationMessageReceived);
}
private void NotificationMessageReceived(NotificationMessage<Hotel> selectedHotel) {
this.SelectedHotel = selectedHotel.Content;
}
from the other viewModel, I send a message with the SelectedHotel.
private Hotel _selectedHotel { get; set; }
public Hotel SelectedHotel {
get { return _selectedHotel; }
set {
_selectedHotel = value;
RaisePropertyChanged("SelectedHotel");
Messenger.Default.Send(new NotificationMessage<Hotel>(this, SelectedHotel, "SelectedHotel"));
}
}
In the ItemsViewModel you do not need the OnSelecetedItemChanged handler code at all. Instead, in the MainWindowViewModel store a reference to the ItemsViewModel, and add a handler there:
var ItemsViewModel = itemsVM = new ItemsViewModel();
itemsVm.PropertyChanged += SelectedHotelChanged;
// and then implement the handler:
public void SelectedHotelChanged(object sender, PropertyChangedEventArgs args)
{
SelectedHotel = itemsVM.SelectedHotel;
}
// ensuring that the SelectedHotel property in the MainWindowViewModel also notifies when it changes.
Edit: Fixed a typo.
Related
I'm trying to make use of EntityFramework and WPF data binding for the first time.
I have some ListBox. I have set ItemsSource to SomeDbContext.SomeEntity.ToList(); programatically and I have set my binding like this:
<ListBox Name="listbox" Margin="4" SelectedValuePath="Address" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Id}"></Label>
<Label Content="{Binding Address}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Click="ButtonTest_Click">Open</Button>
I'm adding new item to my DbSet and I expected that my list will refresh after SomeDbContext.SaveChanges(); method call, but it didn't.
My Window code behind:
DatabaseContext _dbContext = new DatabaseContext();
public MainWindow()
{
InitializeComponent();
lb.ItemsSource = _dbContext.Addresses.ToList();
// I have tried to set source to _dbContext
}
private void ButtonTest_Click(object sender, RoutedEventArgs e)
{
_dbContext.Addresses.Add(new Adresses() { Address = "192.168.1.2:502" });
_dbContext.SaveChanges();
}
Here is my Entity:
public class Adresses
{
public int Id { get; set; }
public string Address { get; set; }
}
My DbContext:
public class DatabaseContext : DbContext
{
public DbSet<Adresses> Addresses { get; set; }
}
What I am doing wrong?
I guess that my approach is wrong, because I'm creating new object when I'm setting ItemsSource to _dbContext.Addresses.ToList();, but I have no idea how to bind directly to my DbSet (or is it possible).
I have strange WPF ObservableCollection behavior. By unclear reason when collection modified and there is another condition in getter-method in some property of my class, it does't modify View. Although CollectionChanged event was invoked!
Without condition in getter method collection works good.
Too complicated and long-winded to explain here what I do in my work project. Therefore I make small simplify project and emulate same behavior. This project show you problem better then thousand words.
To see the problem - launch project as it is, looks how it works. It is really simple, 2 radiobuttons, datagrid and nothing else. Then go to the MainWindowViewModel, GridItems-property, uncomment commented code and launch project again. See the difference. When collection modify, get-method of GridItems-property dont't invoke (I check it with debugger). How not invoked method can make affect on something??? I don't have any idea on it. Help plz.
Project link:
http://www.megafileupload.com/en/file/443850/ObservableCollection-zip.html
class MainWindowViewModel : ViewModelBase
{
private ObservableCollection<GridItem> _totalStorage;
private ObservableCollection<GridItem> _gridItems;
public ObservableCollection<GridItem> GridItems
{
get
{
//if (_gridItems.Count == 0)
//{
// return _totalStorage;
//}
return _gridItems;
}
set
{
_gridItems = value;
RaisePropertyChanged("GridItems");
}
}
public MainWindowViewModel()
{
_totalStorage = new ObservableCollection<GridItem>();
_gridItems = new ObservableCollection<GridItem>();
GridItemsInit();
_gridItems.CollectionChanged += CollectionChanged;
}
/// <summary>
/// Collection change event handler
/// </summary>
/// <param name="o"></param>
/// <param name="e"></param>
private void CollectionChanged(object o, NotifyCollectionChangedEventArgs e)
{
}
private void GridItemsInit()
{
_totalStorage.Add(new GridItem
{
Name = "Igor",
LastName = "Balachtin",
FilerField = FileStatusEnum.All
});
_totalStorage.Add(new GridItem
{
Name = "Misha",
LastName = "Ivanov",
FilerField = FileStatusEnum.All
});
_totalStorage.Add(new GridItem
{
Name = "Ahmed",
LastName = "Magamed",
FilerField = FileStatusEnum.All
});
_totalStorage.Add(new GridItem
{
Name = "abrek",
LastName = "cheburek",
FilerField = FileStatusEnum.All
});
_totalStorage.Add(new GridItem
{
Name = "Irka",
LastName = "Dirka",
FilerField = FileStatusEnum.All
});
}
private void RefreshGridSource(string statusParam)
{
_gridItems.Clear();
//Если нажали на баттон new
if (statusParam.Equals(FileStatusEnum.All.ToString()))
{
foreach (var item in _totalStorage)
{
_gridItems.Add(item);
}
}
//Если нажали на archived
else if (statusParam.Equals(FileStatusEnum.Filtered.ToString()))
{
foreach (var item in _totalStorage.Where(g => g.FilerField == FileStatusEnum.Filtered))
{
_gridItems.Add(item);
}
}
}
private RelayCommand<object> _radioCommand;
public RelayCommand<object> RadioCommand
{
get { return _radioCommand ?? (_radioCommand = new RelayCommand<object>(HandlerFileRadio)); }
}
private void HandlerFileRadio(object obj)
{
if (obj == null)
return;
var statusParam = obj.ToString();
RefreshGridSource(statusParam);
}
}
Look at this sample.
//if (_gridItems.Count == 0)
//{
// return _totalStorage;
//}
Model:
public enum FileStatusEnum
{
All = 0,
Filtered
}
public class GridItem
{
public String Name { get; set; }
public String LastName { get; set; }
public FileStatusEnum FilerField
{
get; set;
}
}
Xaml:
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<RadioButton Margin="5" IsChecked="True" Command="{Binding RadioCommand}"
CommandParameter="All">All</RadioButton>
<RadioButton Margin="5" Command="{Binding RadioCommand}"
CommandParameter="Filtered">Filtered</RadioButton>
</StackPanel>
<DataGrid Grid.Column="1" ItemsSource="{Binding GridItems}" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True" />
<DataGridTextColumn Header="LastName" Binding="{Binding LastName}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
</Grid>
really better post all code here instead of link? :/
Once you are changing record after that your property is not Notifying.so please Notify after changing the collection.
Add below line in RefreshGridSource method after collection changed .
RaisePropertyChanged("GridItems");
Your GridItems property can return either _totalStorage or _gridItems depending upon a condition; _totalStorage and _gridSettings are two different instances of ObservableCollection. Initially, when _gridItems has no items, your GridItems property returns _totalStorage to WPF, and WPF listens on this instance for any CollectionChanged events.
In your RefreshGridSource method you are updating _gridItems (a differnt instance from _totalStorage), which WPF has no knowledge of.
But, when you rasie property changed for GridItems property from RefreshGridSource method WPF will re-read the property GridItems - this time, WPF gets _gridItems collection and it works as you expected.
Hope, I have explained well enough.
I am using below Datagrid, (using MVVM pattern), here what I want is when I select something in the combobox, some kind of notification should happen in the ViewModel saying that this Row’s combobox selectedItem is changed to this value. Right now the notification is happening in the Set method of SelectedEname which is inside class SortedDetails(custom entity) and not a part of viewmodel. Please have a look at the code below and let me know If we can send the notification to videmodel in any way using MVVM pattern.
<c1:C1DataGrid x:Name="datagrid1" ItemsSource="{Binding Path=SortedDetailsList,Mode=TwoWay}" AutoGenerateColumns="False">
<c1:C1DataGrid.Columns>
<c1:DataGridTextColumn Header="Name" Binding="{Binding Name, Mode=TwoWay}"/>
<c1:DataGridTemplateColumn Header="ENGAGEMENT">
<c1:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="cmbEngagement" ItemsSource="{Binding EDetails, Mode=TwoWay}" DisplayMemberPath="EName" SelectedItem="{Binding SelectedEName,Mode=TwoWay}">
</ComboBox>
</DataTemplate>
</c1:DataGridTemplateColumn.CellTemplate>
</c1:DataGridTemplateColumn>
</c1:C1DataGrid.Columns>
</c1:C1DataGrid>
SortedDetailsList is a list of SortedDetails entity, which looks like this :-
public class SortedDetails
{
Private string name;
Private ObservableCollection<details> eDetails;
Private details selectedEname;
public string Name
{
get { return name; }
set { name = value; }
}
public ObservableCollection<details> EDetails
{
get { return eDetails; }
set { eDetails = value; }
}
public details SelectedEname
{
get { return selectedEname; }
set { selectedEname = value; }
}
}
public class Details
{
Private string eName;
Private int eId;
public string EName
{
get { return eName; }
set { eName = value; }
}
public int EId
{
get { return eId; }
set { eId = value; }
}
}
The reason i was asking this question was because i was looking to avoid writing code in codebehind, but in this case not able to avoid the same. So, here is the solution (for me) :-
Add an event delegate or any mediator pattern which will inform the ViewModel that selection is changed from the SelectionChanged event of Combobox...
You can put your ViewModel in the View's resources and bind to the property of ViewModel:
<ComboBox x:Name="cmbEngagement" ItemsSource="{Binding EDetails, Mode=TwoWay}" DisplayMemberPath="EName" SelectedItem="{Binding SelectedEName, Mode=TwoWay, Source={StaticResource ViewModel}">
where SelectedEName is a property of your ViewModel.
You want to use some mechanism for allowing events to invoke commands or verbs (methods) on your view model.
For example, using Actions in Caliburn.Micro, you could write the following:
<ComboBox x:Name="cmbEngagement" ...
cal:Message.Attach="[Event SelectionChanged] = [Action EngagementChanged($dataContext)]>
and in your view model:
public void EngagementChanged(SortedDetails details)
{
// access details.Name here
}
Note that actions in Caliburn.Micro bubble, so it would first look for an EngagementChanged method on SortedDetails type, and then look on your view model.
I'm rather new to Silverlight and have a question about the notifying-mechanism. My solution is an MVVM-application stacked like this:
VIEW Contains a RadGridView bound to a collection in the viewmodel, the data is an entitycollection. The GridView's SelectedItem is bound to corresponding property in the viewmodel.
VIEWMODEL
Holds the properties below that the GridView is bound to and implements INotifyPropertyChanged.
•SelectList - an entitycollection that inherits ObservableCollection. When SelectList is set, it runs a notify-call.
•SelectedItem - an entity that also implements INotifyPropertyChanged for its own properties. When SelectedItem is set, it runs a notify-call.
My question is, who should make the notify-call so that the GridView knows value has changed? Occasionally, a property in the entity is set programmatically directly in the viewmodel. As for now, nothing is happening in the GUI although the properties gets the new values correctly.
Regards, Clas
-- UPDATE WITH CODE -------------------------
VIEW
<UserControl
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
x:Class="X.Y.Z.MonthReport.MonthReportView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot">
<telerik:RadGridView x:Name="MonthReportGrid"
Grid.Row="1"
ItemsSource="{Binding SelectList}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
AutoGenerateColumns="False">
<telerik:RadGridView.Columns>
<!-- The other columns have been cut out of this example -->
<telerik:GridViewDataColumn DataMemberBinding="{Binding curDate, Mode=TwoWay, TargetNullValue=''}" DataFormatString="{} {0:d}" Header="Avläst datum" UniqueName="curDate" IsVisible="True" IsReadOnly="False">
<telerik:GridViewDataColumn.CellEditTemplate>
<DataTemplate>
<telerik:RadDateTimePicker SelectedValue="{Binding curDate, Mode=TwoWay, TargetNullValue=''}" InputMode="DatePicker" DateTimeWatermarkContent="ÅÅÅÅ-MM-DD" />
</DataTemplate>
</telerik:GridViewDataColumn.CellEditTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewDataColumn DataMemberBinding="{Binding curValue, Mode=TwoWay, TargetNullValue=''}" Header="Avläst värde" UniqueName="curValue" IsVisible="True" IsReadOnly="False" />
</telerik:RadGridView>
</Grid>
</UserControl>
VIEW .CS
using System;
using System.Collections.Generic;
using System.Windows.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Windows.Controls;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
namespace X.Y.Z.MonthReport
{
public partial class MonthReportView : UserControl, IMonthReportView
{
/// <summary>
/// ViewModel attached to the View
/// </summary>
public IMonthReportViewModel Model
{
get { return this.DataContext as IMonthReportViewModel; }
set { this.DataContext = value; }
}
public MonthReportView()
{
InitializeComponent();
this.MonthReportGrid.CellEditEnded += new EventHandler<GridViewCellEditEndedEventArgs>(MonthReportGrid_OnCellEditEnded);
}
public void MonthReportGrid_OnCellEditEnded(object sender, GridViewCellEditEndedEventArgs e)
{
if (e.Cell.Column.UniqueName == "curValue")
{
// ...
this.Model.SetAutomaticReadingDate();
}
if (e.Cell.Column.UniqueName == "curDate")
{
this.Model.UpdateAutomaticReadingDate();
}
}
}
}
VIEWMODEL
using System;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Prism.Commands;
namespace X.Y.Z.MonthReport
{
public class MonthReportViewModel : ViewModel<IMonthReportView>, IMonthReportViewModel
{
private readonly IEventAggregator eventAggregator;
private readonly IMonthReportService dataService;
private readonly IMonthReportController dataController;
private DateTime? _newReadingDate;
public DateTime? NewReadingDate
{
get { return _newReadingDate; }
set { _newReadingDate = value; }
}
//Holds the selected entity
private MonthReportEntity _selectedItem;
public MonthReportEntity SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem != value)
{
_selectedItem = value;
//The INotifyPropertyChanged implementation inherited from ViewModel-base.
Notify(() => this.SelectedItem);
}
}
}
//The entitycollection
private MonthReportEntityCollection _selectList;
public MonthReportEntityCollection SelectList
{
get { return _selectList; }
set
{
if (_selectList != value)
{
_selectList = value;
//The INotifyPropertyChanged implementation inherited from ViewModel-base.
Notify(() => this.SelectList);
}
}
}
public MonthReportViewModel(IMonthReportView view,
IEventAggregator eventAggregator, IMonthReportService dataService, IMonthReportController dataController)
{
this.InitializeCommands();
this.eventAggregator = eventAggregator;
this.dataController = dataController;
this.dataService = dataService;
this.View = view;
this.View.Model = this;
dataService.onGetMonthReportComplete += new EventHandler<MonthReportEventArgs>(OnGetMonthReportComplete);
dataService.onSaveMonthReportComplete += new EventHandler<MonthReportEventArgs>(OnSaveMonthReportComplete);
InitializeData();
}
public void InitializeCommands()
{
// ...
}
public void InitializeData()
{
GetMonthReport();
}
//This function is not working as I want it to.
//The gridview doesn't notice the new value.
//If a user edits the grid row, he should not need to
//add the date manually, Therefor I use this code snippet.
public void SetAutomaticReadingDate()
{
if ((NewReadingDate.HasValue) && (!SelectedItem.curDate.HasValue))
{
SelectedItem.curDate = NewReadingDate;
//The INotifyPropertyChanged implementation inherited from ViewModel-base.
Notify(() => this.SelectedItem.curDate);
}
}
public void GetMonthReport()
{
dataService.GetMonthReport();
}
public void SaveMonthReport()
{
dataService.SaveMonthReport(SelectList);
}
void OnGetMonthReportComplete(object sender, MonthReportEventArgs e)
{
// ...
}
void OnSaveMonthReportComplete(object sender, MonthReportEventArgs e)
{
// ...
}
#region ICleanable
public override void Clean()
{
base.Clean();
}
#endregion
}
}
if you do your binding like this
<telerik:GridViewDataColumn DataMemberBinding="{Binding curValue, Mode=TwoWay, TargetNullValue=''}" Header="Avläst värde" UniqueName="curValue" IsVisible="True" IsReadOnly="False" />
you just have to look at the binding to know where you have to call PropertyChanged and your binding said:
the class whith the property "curValue" has to implement INotifyProperyChanged to get the View informed.
public void SetAutomaticReadingDate()
{
if ((NewReadingDate.HasValue) && (!SelectedItem.curDate.HasValue))
{
//this is enough if the class of SelectedItem implements INotifyPropertyChanged
//and the curDate Poperty raise the event
SelectedItem.curDate = NewReadingDate;
}
}
btw BAD code style to name the Property curDate! it should be CurDate, Properties with camlCase hurts my eyes :)
Your "MonthReportEntityCollection" must implement interface "INotifyCollectionChanged" to allow informing UI about collection changes (items add/remove).
Your "MonthReportEntity" must implement interface "INotifyPropertyChanged" to allow informing UI about entitie's property changing.
Other stuff looks correct.
My question: How do I bind the SelectedItem from a primary datagrid to the ItemsSource for a secondary datagrid?
In detail:
I have two datagrids on my view. The first shows a collection of teams and the second shows as list of people in the selected team.
When I select a team from the grid I can see that the SelectedTeam property is getting updated correctly, but the People grid is not getting populated.
Note: I am not able to use nested grids, or the cool master-detail features provided in the SL data-grid.
UPDATE: Replacing the parent datagrid with a ComboBox gives completely different results and works perfectly. Why would ComboBox.SelectedItem and DataGrid.SelectedItem behave so differently?
Thanks,
Mark
Simple Repro:
VIEW:
<UserControl x:Class="NestedDataGrid.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data">
<StackPanel x:Name="LayoutRoot">
<TextBlock Text="Teams:" />
<data:DataGrid ItemsSource="{Binding Teams}"
SelectedItem="{Binding SelectedTeam, Mode=TwoWay}"
AutoGenerateColumns="False">
<data:DataGrid.Columns>
<data:DataGridTextColumn Header="Id" Binding="{Binding TeamId}" />
<data:DataGridTextColumn Header="Desc" Binding="{Binding TeamDesc}" />
</data:DataGrid.Columns>
</data:DataGrid>
<TextBlock Text="Peeps:" />
<data:DataGrid ItemsSource="{Binding SelectedTeam.People}"
AutoGenerateColumns="False">
<data:DataGrid.Columns>
<data:DataGridTextColumn Header="Id"
Binding="{Binding PersonId}" />
<data:DataGridTextColumn Header="Name"
Binding="{Binding Name}" />
</data:DataGrid.Columns>
</data:DataGrid>
</StackPanel>
</UserControl>
CODE_BEHIND:
using System.Windows.Controls;
namespace NestedDataGrid
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.LayoutRoot.DataContext = new ViewModel();
}
}
}
VIEWMODEL:
using System.Collections.ObjectModel;
namespace NestedDataGrid
{
public class ViewModel: ObjectBase
{
public ViewModel()
{
ObservableCollection<Person> RainbowPeeps = new ObservableCollection<Person>()
{
new Person(){ PersonId=1, Name="George"},
new Person(){ PersonId=2, Name="Zippy"},
new Person(){ PersonId=3, Name="Bungle"},
};
ObservableCollection<Person> Simpsons = new ObservableCollection<Person>()
{
new Person(){ PersonId=4, Name="Moe"},
new Person(){ PersonId=5, Name="Barney"},
new Person(){ PersonId=6, Name="Selma"},
};
ObservableCollection<Person> FamilyGuyKids = new ObservableCollection<Person>()
{
new Person(){ PersonId=7, Name="Stewie"},
new Person(){ PersonId=8, Name="Meg"},
new Person(){ PersonId=9, Name="Chris"},
};
Teams = new ObservableCollection<Team>()
{
new Team(){ TeamId=1, TeamDesc="Rainbow", People=RainbowPeeps},
new Team(){ TeamId=2, TeamDesc="Simpsons", People=Simpsons},
new Team(){ TeamId=3, TeamDesc="Family Guys", People=FamilyGuyKids },
};
}
private ObservableCollection<Team> _teams;
public ObservableCollection<Team> Teams
{
get { return _teams; }
set
{
SetValue(ref _teams, value, "Teams");
}
}
private Team _selectedTeam;
public Team SelectedTeam
{
get { return _selectedTeam; }
set
{
SetValue(ref _selectedTeam, value, "SelectedTeam");
}
}
}
}
ASSOCIATED CLASSES:
using System;
using System.ComponentModel;
namespace NestedDataGrid
{
public abstract class ObjectBase : Object, INotifyPropertyChanged
{
public ObjectBase()
{ }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void _OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler pceh = PropertyChanged;
if (pceh != null)
{
pceh(this, new PropertyChangedEventArgs(propertyName));
}
}
protected virtual bool SetValue<T>(ref T target, T value, string propertyName)
{
if (Object.Equals(target, value))
{
return false;
}
target = value;
_OnPropertyChanged(propertyName);
return true;
}
}
public class Person: ObjectBase
{
private int _personId;
public int PersonId
{
get { return _personId; }
set
{
SetValue(ref _personId, value, "PersonId");
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
SetValue(ref _name, value, "Name");
}
}
}
public class Team : ObjectBase
{
private int _teamId;
public int TeamId
{
get { return _teamId; }
set
{
SetValue(ref _teamId, value, "TeamId");
}
}
private string _teamDesc;
public string TeamDesc
{
get { return _teamDesc; }
set
{
SetValue(ref _teamDesc, value, "TeamDesc");
}
}
private ObservableCollection<Person> _people;
public ObservableCollection<Person> People
{
get { return _people; }
set
{
SetValue(ref _people, value, "People");
}
}
}
}
UPDATE
Replacing the first datagrid with a combobox and eveything works OK. Why would DataGrid.SelectedItem and ComboBox.SelectedItem behave so differently?
<StackPanel x:Name="LayoutRoot">
<TextBlock Text="Teams:" />
<ComboBox SelectedItem="{Binding SelectedTeam, Mode=TwoWay}"
ItemsSource="{Binding Teams}"/>
<TextBlock Text="{Binding SelectedTeam}" />
<TextBlock Text="Peeps:" />
<data:DataGrid ItemsSource="{Binding SelectedTeam.People}" />
</StackPanel>
Having done some tests.
First I just wanted to confirm that the Binding itself is working. It works quite happly when the second DataGrid is swapped out for a ListBox. I've gone so far to confirm that the second DataGrid is having its ItemsSource property changed by the binding engine.
I've also swapped out the first DataGrid for a ListBox and then the second DataGrid starts working quite happly.
In addition if you wire up the SelectionChanged event on the first datagrid and use code to assign directly to the second datagrid it starts working.
I've also removed the SelectedItem binding on the first Grid and set up an ElementToElement bind to it from the on the ItemsSource property of the second Grid. Still no joy.
Hence the problem is narrowed down to SelectedItem on one DatGrid to the ItemsSource of another via the framework binding engine.
Reflector provides a possible clue. The Data namespace contains an Extensions static class targeting DependencyObject which has an AreHandlersSuspended method backed bye a static variable. The which the code handling changes to the ItemsSource property uses this method and does nothing if it returns true.
My unconfirmed suspicion is that in the process of the first Grid assigning its SelectedItem property it has turned on the flag in order to avoid an infinite loop. However since this flag is effectively global any other legitmate code running as a result of this SelectedItem assignment is not being executed.
Anyone got SL4 and fancy testing on that?
Any MSFTers lurking want to look into?
If SL4 still has it this will need reporting to Connect as a bug.
A better solution is to use add DataGridRowSelected command. This fits the MVVM pattern a whole lot better than my previous mouse click example.
This was inspired by some code from John Papa, I have created a detailed post about this http://thoughtjelly.blogspot.com/2009/12/binding-selecteditem-to-itemssource.html.
[Sits back contented and lights a cigar]
Mark
I had the same problem, and "fixed" it by adding this to my code-behind.
Code behind:
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_model != null)
{
_model.RefreshDetail();
}
}
Model:
public void RefreshDetail()
{
RaisePropertyChanged("Detail");
}
I have a work-around. It involves a bit of code behind, so won't be favoured by purist MVVM zealots! ;-)
<StackPanel x:Name="LayoutRoot">
<TextBlock Text="Teams:" />
<data:DataGrid x:Name="dgTeams"
SelectedItem="{Binding SelectedTeam, Mode=TwoWay}"
ItemsSource="{Binding Teams}" />
<TextBlock Text="{Binding SelectedTeam}" />
<TextBlock Text="Peeps:" />
<data:DataGrid x:Name="dgPeeps" />
</StackPanel>
Code Behind:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.LayoutRoot.DataContext = new ViewModel();
dgTeams.MouseLeftButtonUp += new MouseButtonEventHandler(dgTeams_MouseLeftButtonUp)
}
void dgTeams_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
DataGridRow row = DependencyObjectHelper.FindParentOfType<DataGridRow>(e.OriginalSource as DependencyObject);
///get the data object of the row
if (row != null && row.DataContext is Team)
{
dgPeeps.ItemsSource = (row.DataContext as Team).People;
}
}
}
The FindParentOfType method is detailed here: http://thoughtjelly.blogspot.com/2009/09/walking-xaml-visualtree-to-find-parent.html.
Hope this helps someone else.