目前在用wpf的时候发现个奇怪的问题:在嵌套的控件里面,如果有控件调用了事件处理程序和使用了ContentTemplateSelector时,程序就会提示:Object reference not set to an instance of an object.。删掉其中任何一个就不会出错 <Window x:Class="TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control="clr-namespace:TestApp" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <control:MyTemplateSelector x:Key="bbb"></control:MyTemplateSelector> </Window.Resources> <ItemsControl ItemsSource="{Binding}"> <ItemsControl.ItemTemplate> <DataTemplate > <ItemsControl ItemsSource="{Binding}" DataContext="{Binding Path=ItemsSource, RelativeSource={RelativeSource AncestorType=ItemsControl,Mode=FindAncestor}}"> <ItemsControl.ItemTemplate> <DataTemplate > <WrapPanel > <Button Cursor="Hand" Content="bbbbbbbb" Height="23" Width="75" Click="ShowContextMenu" > </Button> <ContentControl Content="aa" ContentTemplateSelector="{StaticResource bbb}" /> </WrapPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl></Window> cs源码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TestApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<TestClass> data = new List<TestClass>(); data.Add(new TestClass() { date = "aaaa", name = "aa1", username ="姓名"}); data.Add(new TestClass() { date = "bbb", name = "bbb", username = "姓名1" }); this.DataContext = data; } private void ShowContextMenu(object sender, RoutedEventArgs e) { } } public class TestClass:System.ComponentModel.INotifyPropertyChanged { public string name { get; set; } public string date { get; set; } public string username { get; set; } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; } public class MyTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { return null; } } }
源码如下,删除下面的Onclick或者ContentTemplateSelector就正常,同时存在就会报错:
帮你顶一下,没有接触过WPF。
在<ContentControl../>外面包上ContentControl,例如Button:
<Button><ContentControl../></Button>
测试了下你的代码,并不会有任何错误提示,一切正常