我真的不知道是什麼原因造成的,但我將嫌疑人縮小到DataGrid
,ComboBox.SelectedIndex
屬性或標記擴展名。如果我替換這三個中的任何一個,問題就會消失,或者顯示出更加不可逾越的錯誤。
主窗口:(帶有一個可編輯列中的數據網格)
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication2"
Title="MainWindow"
Height="350"
Width="525"
>
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Column 1" Width="120">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Description}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox SelectedIndex="{src:ValidatedBinding SelectedIndex}"
VerticalAlignment="Center" HorizontalAlignment="Center" Width="100">
<ComboBoxItem>Not Specified</ComboBoxItem>
<ComboBoxItem>First</ComboBoxItem>
<ComboBoxItem>Second</ComboBoxItem>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
代碼驅動此窗口:
using System.Windows;
namespace WpfApplication2
{
/// <summary>
/// The main window.
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//DataContext = new Item { Description = "Item 1", SelectedIndex = 0 };
DataContext = new DemoDataContext();
}
}
/// <summary>
/// An object with 'Items'.
/// </summary>
public sealed class DemoDataContext
{
readonly Item[] _items = new Item[] {
new Item { Description = "Item 1", SelectedIndex = 0 },
new Item { Description = "Item 2", SelectedIndex = 1 },
new Item { Description = "Item 3", SelectedIndex = 2 },
};
public Item[] Items { get { return _items; } }
}
/// <summary>
/// An object with a string and an int property.
/// </summary>
public sealed class Item
{
int _selectedIndex;
string _description;
public string Description
{
get { return _description; }
set { _description = value; }
}
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; }
}
}
}
標記擴展代碼:
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace WpfApplication2
{
/// <summary>
/// Creates a normal Binding but defaults NotifyOnValidationError and ValidatesOnExceptions to True,
/// Mode to TwoWay and UpdateSourceTrigger to LostFocus.
/// </summary>
[MarkupExtensionReturnType(typeof(Binding))]
public sealed class ValidatedBinding : MarkupExtension
{
public ValidatedBinding(string path)
{
Mode = BindingMode.TwoWay;
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
Path = path;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var Target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
/* on combo boxes, use an immediate update and validation */
DependencyProperty DP = Target.TargetProperty as DependencyProperty;
if (DP != null && DP.OwnerType == typeof(System.Windows.Controls.Primitives.Selector)
&& UpdateSourceTrigger == UpdateSourceTrigger.LostFocus) {
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
}
return new Binding(Path) {
Converter = this.Converter,
ConverterParameter = this.ConverterParameter,
ElementName = this.ElementName,
FallbackValue = this.FallbackValue,
Mode = this.Mode,
NotifyOnValidationError = true,
StringFormat = this.StringFormat,
ValidatesOnExceptions = true,
UpdateSourceTrigger = this.UpdateSourceTrigger
};
}
public IValueConverter Converter { get; set; }
public object ConverterParameter { get; set; }
public string ElementName { get; set; }
public object FallbackValue { get; set; }
public BindingMode Mode { get; set; }
[ConstructorArgument("path")]
public string Path { get; set; }
public string StringFormat { get; set; }
public UpdateSourceTrigger UpdateSourceTrigger { get; set; }
}
}
當我運行應用程序,我看到這個:
如果我再次點擊第一列,取細胞進入編輯模式,我得到這個異常:
System.NullReferenceException was unhandled HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=PresentationFramework StackTrace: at System.Windows.Data.BindingExpressionBase.ConvertValue(Object value, DependencyProperty dp, Exception& e) at System.Windows.Data.BindingExpressionBase.ConvertFallbackValue(Object value, DependencyProperty dp, Object sender) at System.Windows.Data.BindingExpressionBase.get_FallbackValue() at System.Windows.Data.BindingExpressionBase.UseFallbackValue() at System.Windows.Data.BindingExpressionBase.get_Value() at System.Windows.Data.BindingExpressionBase.GetValue(DependencyObject d, DependencyProperty (trimmed)
如果我簡化了主窗口,並刪除除組合框的一切,取消註釋將創建一個有效的DataContext項目的行,然後我得到這個錯誤:
System.Windows.Markup.XamlParseException occurred
HResult=-2146233087 Message='Set property 'System.Windows.Controls.Primitives.Selector.SelectedIndex' threw an exception.' Line number '19' and line position '39'.
Source=PresentationFramework LineNumber=19 LinePosition=39
StackTrace: at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri) at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at WpfApplication2.MainWindow.InitializeComponent() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\WpfApplication2\MainWindow.xaml:line 1 at WpfApplication2.MainWindow..ctor() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\WpfApplication2\MainWindow.xaml.cs:line 12
InnerException: System.ArgumentException HResult=-2147024809 Message='System.Windows.Data.Binding' is not a valid value for property 'SelectedIndex'. Source=WindowsBase StackTrace: at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal) at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) at System.Windows.Baml2006.WpfMemberInvoker.SetValue(Object instance, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value) InnerException:
你可以發佈的代碼和stacktrace或任何你可能從你的日誌? – 2012-02-24 02:53:07