【问题标题】:Change binding source of a gridviewitem更改 gridviewitem 的绑定源
【发布时间】:2016-09-20 13:09:30
【问题描述】:

我有一个GridView,其中ItemsSource 绑定到StreamCollections 列表。在ItemsTemplateSelector 中,我根据StreamCollection 的值更改DataTemplate

protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
    FrameworkElement element = container as FrameworkElement;
    if (element != null && item is StreamCollection)
    {
        StreamCollection stream = (StreamCollection) item;
        if (stream.Playlist != null)
        {
            return Application.Current.Resources["PlaylistDataTemplate"] as DataTemplate;
        }
        if (stream.Track != null)
        {               
            return Application.Current.Resources["TrackDataTemplate"] as DataTemplate;
        }
    }
    return null;
}

如果Playlist 不是null,则GridViewItem 应该绑定PlaylistTrack 相同。 FrameworkElement 元素的类型为 GridViewItem,但我似乎找不到对 BindingSource 的任何引用。

【问题讨论】:

  • XAML 代码是什么?您可以尝试不使用模板选择器,以确保您的 XAML 代码和绑定适用于其中一种元素类型(例如轨道)吗?
  • 绑定适用于元素 Track 和播放列表。但在我的列表中,可以有 2 种不同的类型,曲目或播放列表。这就是为什么我制作一个绑定到 StreamCollection 的 GridView(它包含一个属性轨道和播放列表)
  • 我了解您的列表和列表元素的绑定在使用 TemplateSelector 时不起作用。因此,您能否尝试不使用它来检查问题是否真的在这里。或者如果那不是您的问题,请详细说明您的问题?
  • 请发布 xaml 代码
  • 我测试了你发布的代码,它在我身边运行良好,但我很好奇你的StreamCollection是什么,我认为这是你GridView的数据模型类,里面有两个属性PlaylistTrack,这两个属性的数据类型是什么?当我试图重现您的问题时,我将这两个属性设置为List<string>。你把你的两个DataTemplates 放在哪里了?当您使用Application 资源时,您可以将它们放入 App.xaml 文件中。如果仍有问题,请发布您的 xaml 代码和数据模型。

标签: c# binding grid uwp uwp-xaml


【解决方案1】:

不确定它是否有帮助,但是当我有类似的需求时,我已经从应用程序中删除了字典:

 App.Current.Resources.MergedDictionaries.Remove(App.Current.Resources.MergedDictionaries.Last());

并添加了新的

ResourceDictionary dict = new ResourceDictionary();
dict.Source = new Uri("ms-appx:AppStyle1.xaml");
Application.Current.Resources.MergedDictionaries.Add(dict);

因此,您可以尝试将模板放入字典中并以这种方式替换它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2014-08-17
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多