Ale*_*lek 5 c# xaml windows-10 compiled-bindings uwp
我正在尝试掌握新的编译绑定,但是一开始我就被这个简单的问题阻止了。
我有Hub一个控制HubSection。本节的内容是ItemsControl需要绑定到视图模型的可观察集合。我无法让这个绑定像我期望的那样工作。
<Pivot x:Name="rootPivot" Style="{StaticResource TabsStylePivotStyle}">
<PivotItem>
<Hub>
<HubSection Header="News">
<DataTemplate x:DataType="local:HomePage">
<ItemsControl ItemsSource="{x:Bind ViewModel.NewsItems, Mode=OneWay}" />
Run Code Online (Sandbox Code Playgroud)
ViewModelproperty 只是一个属性,在InitializeComponents()调用之前被实例化。NewsItems是在页面加载后填充的视图模型中的可观察集合 - 异步(Web 请求)。
我在这里做错了什么?
编辑:代码隐藏
主页.xaml.cs
/// <summary>
/// Home pag view.
/// </summary>
public sealed partial class HomePage : Page
{
/// <summary>
/// Initializes a new instance of the <see cref="HomePage"/> class.
/// </summary>
public HomePage()
{
// Retrieve view model
this.ViewModel = ViewModelResolver.Home;
// Trigger view model loaded on page loaded
this.Loaded += (sender, args) => this.ViewModel.LoadedAsync();
this.InitializeComponent();
}
/// <summary>
/// Gets the view model.
/// </summary>
/// <value>
/// The view model.
/// </value>
public IHomeViewModel ViewModel { get; }
}
Run Code Online (Sandbox Code Playgroud)
HomePageViewModel.cs
/// <summary>
/// Home view model.
/// </summary>
public sealed class HomeViewModel : IHomeViewModel
{
/// <summary>
/// Occurs on page loaded.
/// </summary>
public async Task LoadedAsync()
{
// Retrieve news items
var news = await new NewsService().GetNewsAsync();
foreach (var newsItem in news)
this.NewsItems.Add(newsItem);
}
/// <summary>
/// Gets the news items.
/// </summary>
/// <value>
/// The news items.
/// </value>
public ObservableCollection<IFeedItem> NewsItems { get; } = new ObservableCollection<IFeedItem>();
}
Run Code Online (Sandbox Code Playgroud)
这确实是一个有趣的问题。我想问题是,DataTemplate与下面的典型不同(请参阅其父级ListView绑定到一些已知数据Model.Items)
<ListView ItemsSource="{x:Bind Model.Items}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Item">
<Grid>
<TextBlock Text="{x:Bind Name}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)
然而,您的最高层DataTemplate不知道数据来自哪里。
因此解决方法是告诉HubSection绑定正确的数据 - 在本例中为实例HomePage.xaml.cs。所以,尝试将其添加到您的Hub
<Hub DataContext="{x:Bind}">
Run Code Online (Sandbox Code Playgroud)
或者简单地添加
this.InitializeComponent();
this.DataContext = this;
Run Code Online (Sandbox Code Playgroud)
无论哪种方式都应该解决您的问题。
| 归档时间: |
|
| 查看次数: |
719 次 |
| 最近记录: |