我有這個頁面:NewsPage
UWP綁定到用戶控件的觀察到的集合不工作
<Page
x:Class="TouchTypeRacing.Views.NewsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TouchTypeRacing.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:TouchTypeRacing.Controls"
xmlns:models="using:TouchTypeRacing.Models"
DataContext="{Binding}"
mc:Ignorable="d">
<Grid Background="White">
....
<ScrollViewer Grid.Row="1"
VerticalScrollBarVisibility="Auto"
Margin="5,10,5,0">
<ItemsControl ItemsSource="{Binding Posts}"
x:Name="itemsControl">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="models:Post">
<controls:Post/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Page>
頁的的DataContext綁定到一個視圖模型。 PageViewmModel
datatemplate是一個Post
控件。
頁面上的ItemsControl
的ItemsSource
綁定到視圖模型的Posts
屬性。
public NewsPage()
{
this.InitializeComponent();
_viewModel = new NewsPageViewModel();
DataContext = _viewModel;
}
然後,視圖模型:
public class NewsPageViewModel
{
private ObservableCollection<Post> _posts = new ObservableCollection<Post>();
public ObservableCollection<Post> Posts { get { return _posts; } }
public NewsPageViewModel()
{
GetPosts(_posts);
}
public static void GetPosts(ObservableCollection<Post> posts)
{
posts.Clear();
posts = new ObservableCollection<Post>
{
new Post
{
Id = "1",
DateTime = DateTime.Today,
User = Application.CurrentUser,
Likes = 10,
ImagePath = Application.CurrentUser.ImagePath,
Message = "Test message",
Comments = new ObservableCollection<Comment>
{
new Comment {Id= "1", Content="Comment1", User = Application.CurrentUser },
new Comment {Id= "2", Content="Comment2", User = Application.CurrentUser },
new Comment {Id= "3", Content="Comment3", User = Application.CurrentUser },
new Comment {Id= "4", Content="Comment4", User = Application.CurrentUser },
},
Last2Comments = new List<Comment>
{
new Comment {Id= "3", Content="Comment3", User = Application.CurrentUser },
new Comment {Id= "4", Content="Comment4", User = Application.CurrentUser },
}
}
};
}
的ItemsControl
顯示了空。 我在做什麼錯?
仍然沒有顯示任何內容。我在Quickfix中編輯了Viewmodel。檢查編輯 – shadowCODE
@shadowCODE您可以調用'posts.Clear()',然後將其丟棄並將該參數替換爲新的集合。不要這樣做。這對你所做的任何方法都沒有影響。把這篇文章放在OLD集合中。您必須必須必須保持SAME集合的正常運行。在該代碼中,您開始的集合是UI將會知道的唯一集合。所以這是帖子必須出現的原因。這就是爲什麼這不是一個好的解決方案的原因之一。 –
@shadowCODE請參閱上面的「自我懲罰練習」。 –