我有覆盖问题。我知道你不能覆盖继承的成员,除非它们被标记为虚拟,抽象或覆盖,但是......
我有来自msdn的this code:
using System.Windows;
using System.Windows.Controls;
namespace SDKSample
{
public class TaskListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Task)
{
Task taskitem = item as Task;
if (taskitem.Priority == 1)
return
element.FindResource("importantTaskTemplate") as DataTemplate;
else
return
element.FindResource("myTaskTemplate") as DataTemplate;
}
return null;
}
}
}
我添加了这段代码:
public class PostTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
ListViewItem lvi = item as ListViewItem;
AppNetClient.PostClass key = lvi.DataContext as AppNetClient.PostClass;
if (key.postTemplate == "Post")
{
return lvi.FindName("PostDataTemplate") as DataTemplate;
}
else
{
return lvi.FindName("SelectedPostDataTemplate") as DataTemplate;
}
}
}
我收到了这个错误:
Error 3 'oneSocialLife.MainPage.PostTemplateSelector.SelectTemplate(object, Windows.UI.Xaml.DependencyObject)': cannot override inherited member 'Windows.UI.Xaml.Controls.DataTemplateSelector.SelectTemplate(object, Windows.UI.Xaml.DependencyObject)' because it is not marked virtual, abstract, or override C:\Users\kcone\documents\visual studio 2012\Projects\HttpClientApp\HttpClientApp\MainPage.xaml.cs 339 42 oneSocialLife
我花了几个小时寻找原因,但无法弄明白。有什么想法吗?
答案 0 :(得分:6)
您引用的示例适用于WPF(System.Windows.Controls.DataTemplateSelector)。
在Windows应用商店应用中,您使用的Windows.UI.Xaml.Controls.DataTemplateSelector具有不同的语义,而SelectTemplate确实无法覆盖,但SelectTemplateCore是。
答案 1 :(得分:4)
最终工作的代码: 来自:http://msdn.microsoft.com/en-us/library/ms742521.aspx 还有:http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector
public class PostTemplateSelector : DataTemplateSelector
{
public DataTemplate PostTemplate { get; set; }
public DataTemplate SelectedPostTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
//ListViewItem lvi = item as ListViewItem;
//AppNetClient.PostClass key = lvi.DataContext as AppNetClient.PostClass;
AppNetClient.PostClass key = item as AppNetClient.PostClass;
if (key.postTemplate == "Post")
{
return PostTemplate;
}
else
{
return SelectedPostTemplate;
}
}
}