WinUI3 TabView XAML不更新视图中的数据绑定



目前正在使用C#、WinUI3和XAML开发一个简单的UWP应用程序。很像微软在这里所做的新改变。然而,我遇到了一些奇怪的绑定问题,我无法理解。我使用的是简单的ObservableCollection<ProfileTab> ProfileTabs,它应该用一个选项卡初始化并显示在muxs.TabView中。我只是直接按照XAML控件Galary(https://github.com/microsoft/Xaml-Controls-Gallery/blob/f95e0a2003be53228030dcf72032fcb47b96060f/XamlControlsGallery/ControlPages/TabViewPage.xaml.cs&https://github.com/microsoft/Xaml-Controls-Gallery/blob/f95e0a2003be53228030dcf72032fcb47b96060f/XamlControlsGallery/ControlPages/TabViewPage.xaml)

XAML代码

<TabView Grid.Row="1" TabItemsSource="{x:Bind ProfileTabs, Mode=OneWay}" AddTabButtonClick="TabView_AddButtonClick" TabCloseRequested="TabView_TabCloseRequested">
<TabView.TabItemTemplate>
<DataTemplate x:DataType="local:ProfileTab">
<muxc:TabViewItem Header="{x:Bind TabHeader}" IconSource="{x:Bind TabIconSource}" Content="{x:Bind TabContent}" />
</DataTemplate>
</TabView.TabItemTemplate >
</TabView>

C#代码

public class ProfileTab
{
public string TabHeader { get; set; }
public IconSource TabIconSource { get; set; }
public object TabContent { get; set; }
}
public sealed partial class MainPage : Page
{
public ObservableCollection<ProfileTab> ProfileTabs { get; set; }
public MainPage()
{
this.InitializeComponent();
InitializeSampleProfile();
}
private void TabView_AddButtonClick(TabView sender, object args)
{
var profile = new SettingsProfile("");
ProfileTabs.Add(CreateNewTab(profile));
}
private void TabView_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args)
{
ProfileTabs.Remove(args.Item as ProfileTab);
}
private ProfileTab CreateNewTab(SettingsProfile profile)
{
var profileTab = new ProfileTab
{
TabHeader = $"{profile.PrettyName()}",
TabIconSource = new SymbolIconSource() { Symbol = Symbol.Document },
};
// The content of the tab is a frame that contains a page, pass the profile as parameter
Frame frame = new Frame();
frame.Navigate(typeof(ProfilePage), profile);
profileTab.TabContent = frame;
return profileTab;
}
private void InitializeSampleProfile()
{
ProfileTabs = new ObservableCollection<ProfileTab>();
// load sample data
ProfileTabs.Add(CreateNewTab(defaultProfile));
}
}

现在默认选项卡已经初始化,我觉得很棒!但无论何时单击添加或删除,都不会发生任何事情。我启动了调试器,事件被触发,ObservableCollection似乎确实发生了变化——添加和删除了显示的选项卡。现在的问题是视图本身没有变化——只有一个默认选项卡。

有人可以向我指出错误或解决方法吗?谢谢

我已经测试了上面的代码,它在我这边运行得很好,我在这里做了一个简单的示例,请检查一下。

请注意,TabViewIconSource位于Microsoft.UI.Xaml.Controls命名空间下,请不要使用Windows.UI.Xaml.ControlsIconSource进行替换,否则将键入异常。

最新更新