我在两个页面上分别有两个数据网格,例如父页面上的父网格和子页面上的子网格。如何访问父页面的选定项到子页面?
当两个数据网格都放在同一页面上时,所选项目有效。但是当我在每一页上分别放置网格时,它就不起作用了。
父页面的 XAML
<Grid.Datacontext>
<local:MainViewModel/>
</Grid.Datacontext>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedHost, Mode=TwoWay}" SelectionChanged="DataGrid_SelectionChanged"/>
ParentPage 的代码隐藏
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ChildPage _page = new ChildPage();
this.NavigationService.Navigate(_page);
}
子页面的 XAML
<DataGrid x:Name="ChildDatagrid" Margin="12,104,81,266" ItemsSource="{Binding Details}"/>
主视图模型
//Datacontext
public MainViewModel()
{
this.Persons = Person.GetPersons();
}
// for Person Datagrid
private ObservableCollection<Person> personValues;
public ObservableCollection<Person> Persons
{
get { return personValues; }
set { this.SetProperty<ObservableCollection<Person>>(ref this.personValues, value); }
}
//for the PersonDetails datagrid
public ObservableCollection<PersonDetails> Details
{
get
{
if (this.Selectedperson == null)
{
return null;
}
return this.LoadDetails(this.Selectedperson.PersonID);
}
}
// method to load the persondetails data
private ObservableCollection<PersonDetails> LoadDetails(int personID)
{
ObservableCollection<PersonDetails> details = new ObservableCollection<PersonDetails>();
foreach (PersonDetails detail in PersonDetails.GetDetails().Where(item => item.PersonID == personID))
{
details.Add(detail);
}
return details;
}
// SelectedPerson Property
private Person selectedPersonValue;
public Person Selectedperson
{
get { return selectedPersonValue; }
set
{
this.SetProperty<Person>(ref this.selectedPersonValue, value);
this.RaiseNotification("Details");
}
}