UWP TabView OneWay x:绑定不更新
Posted
技术标签:
【中文标题】UWP TabView OneWay x:绑定不更新【英文标题】:UWP TabView OneWay x:Bind does not update 【发布时间】:2020-01-16 08:57:48 【问题描述】:我有一个TabView
,其ItemTemplate
是这样的:
<controls:TabView.ItemTemplate>
<DataTemplate x:DataType="data:Playlist">
<local:HeaderedPlaylistControl
IsPlaylist="True"
Loaded="HeaderedPlaylistControl_Loaded"
MusicCollection="x:Bind Mode=OneWay" />
</DataTemplate>
</controls:TabView.ItemTemplate>
这是HeaderedPlaylistControl
的一部分:
<local:PlaylistControl
AllowReorder="False"
AlternatingRowColor="True"
ItemsSource="x:Bind MusicCollection.Songs, Mode=OneWay">
<local:PlaylistControl.Header>
<controls:ScrollHeader Mode="Sticky">
<UserControl>
<Grid
x:Name="PlaylistInfoGrid"
Padding="10"
Background="ThemeResource SystemColorHighlightColor">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image
x:Name="PlaylistCover"
Grid.RowSpan="3"
Width="180"
Height="180"
Margin="20"
Source="Assets/monotone_bg_wide.png" />
<TextBlock
x:Name="PlaylistNameTextBlock"
Grid.Column="1"
Margin="0,5"
VerticalAlignment="Center"
FontSize="36"
Foreground="White"
Style="StaticResource HeaderTextBlockStyle"
Text="x:Bind MusicCollection.Name, Mode=OneWay" />
<TextBlock
x:Name="PlaylistInfoTextBlock"
Grid.Row="1"
Grid.Column="1"
Margin="0,5"
VerticalAlignment="Top"
Foreground="White"
Text="x:Bind MusicCollection.Songs, Converter=StaticResource SongCountConverter, Mode=OneWay" />
</Grid>
</UserControl>
</controls:ScrollHeader>
</local:PlaylistControl.Header>
</local:PlaylistControl>
当我在标签之间切换时,HeaderedPlaylistControl
不会更新它的内容。这是为什么呢?
是不是因为MusicCollection
属性(它是Playlist
类型)在切换标签时没有通知绑定?如果是这样,我应该把通知放在哪里? Playlist
的定义是here。
HeaderedPlaylistControl 是here:
【问题讨论】:
【参考方案1】:是的,正如您所怀疑的,问题在于MusicCollection
属性是一个普通属性,它不会通知更改。要使您的代码正常工作,您需要将MusicCollection
属性设置为依赖属性(请参阅docs)。这是一种最适合可视控件的数据绑定属性的属性,并且还具有许多附加功能。
public static readonly DependencyProperty MusicCollectionProperty =
DependencyProperty.Register(
nameof(MusicCollection), typeof(Playlist),
typeof(HeaderedPlaylistControl), null
);
public Playlist MusicCollection
get return (bool)GetValue(MusicCollectionProperty);
set SetValue(MusicCollectionProperty, value);
【讨论】:
以上是关于UWP TabView OneWay x:绑定不更新的主要内容,如果未能解决你的问题,请参考以下文章
将新项目添加到绑定的 ItemsSource 时,WinUI 3 UWP TabView 不显示新选项卡