[英]How to bind to a list that nested deep in the DataContext object in WPF
我需要綁定到隱藏在DataContext對象內部深處的對象列表,它似乎對我不起作用。 這是我的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
的實例。 然后,我在SelectionChanged事件處理程序中為所選用戶動態加載UserSettingsViewModel
對象:
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綁定到Users屬性沒有任何問題,但是由於某種原因,我根本無法顯示Subscriptions屬性。 它只是什么都不做:
<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
不是Binding的合法路徑? 有什么想法嗎?
使用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屬性頁。
您能否嘗試使用此綁定而不是您的綁定:
<ListView ItemsSource="{Binding Path=UserDataContext.UserSettings.Subscriptions}">
基本上,當您這樣做時:
UserDataContext.UserSettings = _usersSettingsDal.ToViewModel(settings);
您應該像@toadflakz所說的那樣引發一個propertychange事件,例如:
RaiseProperyChanged(()=>UserDataContext.UserSettings);
並且綁定也不正確。 正確的是@Greenonion說的:
<ListView ItemsSource="{Binding Path=UserDataContext.UserSettings.Subscriptions}">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.