Hub在控件的HubSection中添加内容都是使用DataTemplate完成的,在hubsection中添加Listview/gridView一样需要使用模板进行数据绑定。有点复杂,但并不难懂,然而使用x:bind进行数据绑定内容不显示。而使用dataContext则没有问题(Binding)。这个问题纠结了我几个小时,最后我在官方的Sample的code里面发现了这样一段代码:
this.DataContext = this; //We have to set the DataContext to itself here to ensure the bindings get hooked up correctly in the Hub.
必须将数据上下文设置为自己确保hub显示绑定,加入这句话之后瞬间解决问题了,这句话藏在codebehind里面不容易注意到,而且这是一个莫名其妙的问题搭配了一个似是而非的解决方案,这真是一个不容易发现的坑啊!
最后贴出绑定的代码:
<HubSection Width="380" Padding="20"
VerticalAlignment="Top" Name="localFilesHub">
<DataTemplate x:DataType="local:UserCenter">
<ListView ItemsSource="{x:Bind StorageFiles,Mode=OneWay}"
ItemTemplate="{StaticResource LocalFilesTemplate}">
</ListView>
</DataTemplate>
</HubSection>
后台
public sealed partial class UserCenter : Page, INotifyPropertyChanged
{
IReadOnlyList<StorageFile> _StorageFiles;
public IReadOnlyList<StorageFile> StorageFiles
{
get { return _StorageFiles; }
set { SetProperty(ref _StorageFiles, value); }
}
//----
public UserCenter()
{
this.InitializeComponent();
GetLocalFiles();
this.DataContext = this;//大坑标记
}
public async void GetLocalFiles()
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFiles= await folder.GetFilesAsync();
}
//实现INotify接口
public event PropertyChangedEventHandler PropertyChanged;
private bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}