を動作していないユーザーコントロールの監視可能なコレクションにバインド: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
ItemsControl
データテンプレートは、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がこれまでに知る唯一のコレクションです。投稿が入る必要があるのはこれです。これが大きな解決策ではない理由の1つです。 –
@shadowCODE上記の「自己罰の行使」を参照してください。 –