2014-09-04 38 views
0

我需要綁定到隱藏在DataContext對象深處的對象列表,它似乎不適用於我。這裏是我的DataContext對象:如何綁定到嵌套在WPF中的DataContext對象深處的列表

public class UserDataContext 
{ 
    public ObservableCollection<UserViewModel> Users { get; set; } 
    public UsersSettingsViewModel UserSettings { get; set; } 
} 


public class UsersSettingsViewModel 
{ 
    public int Id { get; set; } 
    public ObservableCollection<Subscriptions> Subscriptions { get; set; } 
} 

我有一個用戶列表,勢必Users財產,當選擇一個用戶,我想以顯示用戶定義的設置。設置保存在UsersSettingsViewModel類中,目前它只是用戶訂閱的列表。我在開始時將DataContext設置爲UserDataContext的實例。然後,我動態加載UserSettingsViewModel對象在SelectionChanged事件處理程序選定的用戶:

private void OnUserSelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (lwUsers.SelectedItem == null) 
     return; 

    var selectedUser = (UserViewModel)lwUsers.SelectedItem; 
    var settings = _usersSettingsDal.Load(selectedUser.Login) ?? _usersSettingsDal.Create(selectedUser.Login); 
    UserDataContext.UserSettings = _usersSettingsDal.ToViewModel(settings); 
} 

我雖然不具備約束力從XAML用戶財產的任何問題,由於某種原因,我不能得到的訂閱屬性完全顯示。它只是沒有做任何事情:

<GroupBox Header="Subscriptions" Name="gbSubscriptions"> 
          <StackPanel Margin="10,10,10,10"> 
           <ListView ItemsSource="{Binding UserDataContext.Subscriptions}"> 
            <ListBox.ItemTemplate> 
             <DataTemplate> 
              <StackPanel> 
               <TextBlock Text="{Binding Path=Name, diag:PresentationTraceSources.TraceLevel=High}" /> 
               <CheckBox IsChecked="{Binding Path=Enabled, diag:PresentationTraceSources.TraceLevel=High}" /> 
              </StackPanel> 
             </DataTemplate> 
            </ListBox.ItemTemplate> 
           </ListView> 
          </StackPanel> 
         </GroupBox> 

我需要刷新DataContext嗎?或者UserDataContext.Subscriptions不是綁定的合法路徑?有什麼想法嗎?

回答

0

你能嘗試使用此綁定,而不是你的:當你做

<ListView ItemsSource="{Binding Path=UserDataContext.UserSettings.Subscriptions}"> 
0

基本上是:

UserDataContext.UserSettings = _usersSettingsDal.ToViewModel(settings); 

爲@toadflakz說,你應該提出一個PropertyChange事件,類似:

RaiseProperyChanged(()=>UserDataContext.UserSettings); 

而且綁定也是不正確的。正確的是@Greenonion說:

<ListView ItemsSource="{Binding Path=UserDataContext.UserSettings.Subscriptions}"> 
1

使用Binding Path小號引用嵌套的屬性是非常相似的代碼引用相同的屬性。把這些例子:

int age = SomeParent.SomeChild.Age; 

"{Binding Path=SomeParent.SomeChild.Age}" 


SomeObject object = SomeCollection[0].SomeChild.SomeObject; 

"{Binding Path=SomeCollection[0].SomeChild.SomeObject}" 


double value = SomeClass.SomeObjectProperty.SomeCollection[0].SomeProperty; 

"{Binding Path=SomeClass.SomeObjectProperty.SomeCollection[0].SomeProperty}" 

對於Binding Path語法的較大幅度的列表,請在MSDN上查看Binding.Path Property頁面。