Use Popup in EditingTemplateCell: Message=Value cannot be null. Parameter name:descendant - wpf

I'm using a WPF DataGrid and I put a DataGridTemplateColumn. Because the column should perform edit on a complex type (it's an object), I decided to put a togglebutton that open a popup. The code is the follow:
<DataTemplate>
<Grid>
<ToggleButton Grid.Column="2" x:Name="tb" Focusable="false" IsChecked="False" ClickMode="Press" Content="Edit values" />
<Popup IsOpen="{Binding ElementName=tb, Path=IsChecked, Mode=OneWay}" Placement="Bottom" x:Name="Popup" Focusable="False" StaysOpen="False" AllowsTransparency="True" Margin="0,1,0,0">
<Grid x:Name="dd" SnapsToDevicePixels="True">
<Border x:Name="ddb" Margin="0,-1,0,0" BorderBrush="DarkGray" BorderThickness="1" CornerRadius="0,0,3,3" Background="Gray">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="Uno:" Grid.Row="0" Grid.Column="0" />
<TextBox Text="{Binding Path=calendar.uno, Mode=TwoWay, StringFormat={}{0:0.##}}" Grid.Row="0" Grid.Column="1" />
<TextBlock Text="Due:" Grid.Row="1" Grid.Column="0" />
<TextBox Text="{Binding Path=calendar.due, Mode=TwoWay, StringFormat={}{0:0.##}}" Grid.Row="1" Grid.Column="1" />
<TextBlock Text="Tre:" Grid.Row="2" Grid.Column="0" />
<TextBox Text="{Binding Path=calendar.tre, Mode=TwoWay, StringFormat={}{0:0.##}}" Grid.Row="2" Grid.Column="1" />
</Grid>
</Border>
</Grid>
</Popup>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
The popup works, but often the following exception occurs:
System.ArgumentNullException was unhandled
Message=Value cannot be null.
Parameter name: descendant
Source=PresentationCore
ParamName=descendant
StackTrace:
at System.Windows.Media.VisualTreeHelper.IsAncestorOf(DependencyObject ancestor, DependencyObject descendant, Type stopType)
at System.Windows.Controls.DataGridCell.RemoveBindingExpressions(BindingGroup bindingGroup, DependencyObject element)
at System.Windows.Controls.DataGridCell.BuildVisualTree()
at System.Windows.Controls.DataGridCell.OnIsEditingChanged(Boolean isEditing)
at System.Windows.Controls.DataGridCell.OnIsEditingChanged(Object sender, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
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, Boolean value)
at System.Windows.Controls.DataGridCell.BeginEdit(RoutedEventArgs e)
at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs e)
at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(Object sender, ExecutedRoutedEventArgs e)
at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)
at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
at System.Windows.Input.RoutedCommand.Execute(Object parameter, IInputElement target)
at System.Windows.Controls.DataGrid.BeginEdit(RoutedEventArgs editingEventArgs)
at System.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDown(MouseButtonEventArgs e)
at System.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDownThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseDownThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at WpfApplication5.App.Main() in C:\Users\r.sarati\Desktop\WpfDataGridSynchronized_V1.00\WpfDataGridSynchronized\CF40\WpfApplication5\obj\Debug\App.g.cs:line 50
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
What's the problem? (use multiple columns is not a valid alternative)

currently I have this exception in my app too; same stack trace. I found also few solutions for this but these solutions are not very "nice":
1 I used aero style for whole dialog where I have DataGrid to have same look for default controls in different Windows versions (mainly for XP to look controls "nicer"). When I comment following part of code in xaml of dialog no other exception is showing:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PresentationFramework.Aero, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</ResourceDictionary.MergedDictionaries>
But I'm on XP now, I must check if this problem is solved also on Win7.
EDIT: works also for Windows7.
2 Try check this link on microsoft page: http://support.microsoft.com/kb/2498911
3 As it is written also on microsoft page you can still turn off Virtualization for Row or Column of your datagrid but if you have for example 1000 rows it takes some time to load everything :/
EDIT :
4. I downloaded the Aero.NormalColor.xaml (part of themes from microsoft available here: http://msdn.microsoft.com/en-us/library/aa970773.aspx) and add this theme to my app.xaml to app dictionary. It seems that this fixed the problem (probably same look but some differencies in code for this themes).
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/GlassButton.xaml"/>
<ResourceDictionary Source="Themes/Aero.NormalColor.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>

Related

Value does not fall within the expected range error binding in Telerik RadGridView

I am following the example posted by Telerik on how to show/hide columns in their RadGridView control, as shown here:
<StackPanel x:Name="CustomizeGrid" Background="Transparent" Orientation="Horizontal">
<ListBox ItemsSource="{Binding Columns, ElementName=WorklistGridView}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header}" IsChecked="{Binding IsVisible, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<telerik:RadGridView x:Name="WorklistGridView" AutoGenerateColumns="False" RowIndicatorVisibility="Collapsed" IsReadOnly="True" SelectionMode="Multiple"
CanUserSelect="False" IsSynchronizedWithCurrentItem="False" ItemsSource="{Binding Mode=OneWay}" IsFilteringAllowed="True">
<telerik:RadGridView.Columns>
<telerik:GridViewSelectColumn x:Name="Select" IsResizable="False" />
<telerik:GridViewDataColumn Header="Status" DataMemberBinding="{Binding OrderStatusDescription}"/>
<telerik:GridViewDataColumn Header="Patient Name" DataMemberBinding="{Binding PatientName}"/>
But the example is not compiling correctly. The problem is here: CheckBox `Content="{Binding Header}" The main error listed is: Value does not fall within the expected range.
I'm not sure why this is happening. I'll try to post the rest of the error below. Does anyone else have this working, or have any ideas what's up?
System.InvalidOperationException
An unhandled exception was encountered while trying to render the current silverlight project on the design surface. To diagnose this failure, please try to run the project in a regular browser using the silverlight developer runtime. at
Microsoft.Windows.Design.Platform.SilverlightViewProducer.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs e) at Microsoft.Expression.Platform.Silverlight.SilverlightPlatformSpecificView.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs args) at Microsoft.Expression.Platform.Silverlight.Host.SilverlightImageHost.<>c_DisplayClass1.b_0(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
System.ArgumentException Value does not fall within the expected range. at MS.Internal.XcpImports.CheckHResult(UInt32 hr) at MS.Internal.XcpImports.SetValue(IManagedPeerBase obj, DependencyProperty property, DependencyObject doh) at MS.Internal.XcpImports.SetValue(IManagedPeerBase doh, DependencyProperty property, Object obj) at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value) at System.Windows.DependencyObject.SetEffectiveValue(DependencyProperty property, EffectiveValueEntry& newEntry, Object newValue) at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation) at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp) at System.Windows.Data.BindingExpression.SendDataToTarget() at System.Windows.Data.BindingExpression.SourceAcquired() at System.Windows.Data.BindingExpression.System.Windows.IDataContextChangedListener.OnDataContextChanged(Object sender, DataContextChangedEventArgs e) at System.Windows.Data.BindingExpression.DataContextChanged(Object sender, DataContextChangedEventArgs e) at System.Windows.DataContextChangedEventHandler.Invoke(Object sender, DataContextChangedEventArgs e) at System.Windows.FrameworkElement.OnDataContextChanged(DataContextChangedEventArgs e) at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive) at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent) at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent, Byte bCanCreateParent)
I managed to replicate your issue but I receive different exception ("Element is already the child of another element"). I think the reason can be the same so see if it helps.
A little debugging shows that when SelectionMode is set to Multiple then the Header of GridViewSelectColumn becomes a CheckBox. This means that you're trying to add same CheckBox to both column header and CheckBox content inside your ListBox. Just try to remove SelectionMode and see if you have the same issue or not.
If that's the case then you can fix issue by adding a converter to CheckBox.Content binding that passes through only strings. For example:
public class HeaderConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
return value;
return string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then in XAML:
<ListBox ItemsSource="{Binding Columns, ElementName=WorklistGridView}">
<ListBox.Resources>
<local:HeaderConverter x:Key="headerConverter" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header, Converter={StaticResource headerConverter}}"
IsChecked="{Binding IsVisible, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Drag'n Drop Problems with extended glass border

I'm playing around with the glass border in WPF and I've found a problem.
When I extend the glass border of a window, the drag and drop functions won't work anymore... for example dragging a GridSplitter around ends with an exception.
The XAML of my MainWindow:
<Window
x:Class="ChromeDragDrop.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shell="clr-namespace:Microsoft.Windows.Shell;assembly=Microsoft.Windows.Shell"
xmlns:local="clr-namespace:ChromeDragDrop"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="shell:WindowChrome.WindowChrome">
<Setter.Value>
<shell:WindowChrome GlassFrameThickness="-1" ResizeBorderThickness="4" CaptionHeight="36"/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MainWindow}">
<ContentPresenter Content="{TemplateBinding Content}"></ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid Margin="50">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Border Background="Lime" Opacity="0.8"></Border>
<Border Background="Gray" Opacity="0.8" Grid.Row="1"></Border>
<GridSplitter Background="Red" Height="10" ShowsPreview="True" ResizeDirection="Rows" HorizontalAlignment="Stretch" Grid.Row="1" VerticalAlignment="Top"></GridSplitter>
</Grid>
</Window>
The Exception:
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=PresentationFramework
StackTrace:
at System.Windows.Controls.GridSplitter.OnDragDelta(DragDeltaEventArgs e)
at System.Windows.Controls.GridSplitter.OnDragDelta(Object sender, DragDeltaEventArgs e)
at System.Windows.Controls.Primitives.DragDeltaEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.Thumb.OnMouseMove(MouseEventArgs e)
at System.Windows.UIElement.OnMouseMoveThunk(Object sender, MouseEventArgs e)
at System.Windows.Input.MouseEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at ChromeDragDrop.App.Main() in C:\Project\CSharp\Learn\WPF\ChromeGlass\ChromeDragDrop\ChromeDragDrop\obj\x86\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
What can I do to solve this problem?
Have you tried adding an AdronerDecorator at the root of your window? I was getting the same exception, but in my case my WPF control was hosted within an HwndSource in an MFC window. See this MS knowledgebase article for more information.

ListPicker Windows Phone 7 exception

I have a problem with the ListPicker component. I download a sample from: http://code.msdn.microsoft.com/Windows-Phone-71-Local-da2fdf80. It is compile, but when I'd like to change page (contains ListPicker), exception was thrown.
System.Windows.Markup.XamlParseException occurred
Message=Set property 'Microsoft.Phone.Controls.ListPicker.ItemCountThreshold' threw an exception. [Line: 42 Position: 63]
LineNumber=42
LinePosition=63
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at PhoneApp.Views.TaskEditView.InitializeComponent()
at PhoneApp.Views.TaskEditView..ctor()
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type)
at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
InnerException: System.NotSupportedException
Message=Cannot set read-only property 'Microsoft.Phone.Controls.ListPicker.ItemCountThreshold'.
StackTrace:
at MS.Internal.XamlMemberInfo.SetValue(Object target, Object value)
at MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType, XamlQualifiedObject& inObj, XamlPropertyToken inProperty, XamlQualifiedObject& inValue)
at MS.Internal.XcpImports.Application_LoadComponentNative(IntPtr pContext, IntPtr pComponent, UInt32 cUriStringLength, String uriString, UInt32 cXamlStrLength, Byte* pXamlStr, UInt32 cAssemblyStrLength, String assemblyStr)
at MS.Internal.XcpImports.Application_LoadComponent(IManagedPeerBase componentAsDO, String resourceLocator, UnmanagedMemoryStream stream, UInt32 numBytesToRead, String assemblyString)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at PhoneApp.Views.TaskEditView.InitializeComponent()
at PhoneApp.Views.TaskEditView..ctor()
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type)
at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
It is my XAML page:
<local:EntityEditPage
x:Class="PhoneApp.Views.TaskEditView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns:local="clr-namespace:PhoneApp.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="edit task" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer>
<StackPanel>
<!-- title -->
<TextBlock Text="Title" Style="{StaticResource DefaultLabelStyle}" />
<TextBox Text="{Binding Path=Title, Mode=TwoWay}" TextWrapping="Wrap" Style="{StaticResource FormTextBox}" />
<!-- project -->
<TextBlock Text="Project" Style="{StaticResource DefaultLabelStyle}"/>
<toolkit:ListPicker x:Name="listProjects" Style="{StaticResource FormListPicker}">
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<Grid Background="Transparent" Margin="12">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}" />
</Grid>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" />
</Grid>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
<!-- date -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock VerticalAlignment="Center" Text="Date" Style="{StaticResource DefaultLabelStyle}" />
<toolkit:DatePicker x:Name="datePicker" Style="{StaticResource FormDatePicker}" />
</StackPanel>
<StackPanel Grid.Column="1">
<TextBlock VerticalAlignment="Center" Text="Time" Style="{StaticResource DefaultLabelStyle}" />
<toolkit:TimePicker x:Name="timePicker" />
</StackPanel>
</Grid>
<!-- status -->
<TextBlock Text="Status" Style="{StaticResource DefaultLabelStyle}"/>
<toolkit:ListPicker x:Name="listStatus" ListPickerMode="Normal" SelectedItem="{Binding Status, Mode=TwoWay}">
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
<!-- description -->
<TextBlock Text="Description" Style="{StaticResource DefaultLabelStyle}" />
<TextBox Text="{Binding Path=Description, Mode=TwoWay}" Height="285" TextWrapping="Wrap" AcceptsReturn="True" Style="{StaticResource FormTextBox}" />
</StackPanel>
</ScrollViewer>
</Grid>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar>
<shell:ApplicationBarIconButton IconUri="/icons/appbar.check.rest.png" Text="button" Click="OnOK"/>
<shell:ApplicationBarIconButton IconUri="/icons/appbar.cancel.rest.png" Text="button" Click="OnCancel"/>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
</local:EntityEditPage>

Value does not fall within the expected range error binding in RadGridView

I am following the example posted by Telerik on how to show/hide columns in their RadGridView control, as shown here:
<StackPanel x:Name="CustomizeGrid" Background="Transparent" Orientation="Horizontal">
<ListBox ItemsSource="{Binding Columns, ElementName=WorklistGridView}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header}" IsChecked="{Binding IsVisible, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<telerik:RadGridView x:Name="WorklistGridView" AutoGenerateColumns="False" RowIndicatorVisibility="Collapsed" IsReadOnly="True" SelectionMode="Multiple"
CanUserSelect="False" IsSynchronizedWithCurrentItem="False" ItemsSource="{Binding Mode=OneWay}" IsFilteringAllowed="True">
<telerik:RadGridView.Columns>
<telerik:GridViewSelectColumn x:Name="Select" IsResizable="False" />
<telerik:GridViewDataColumn Header="Status" DataMemberBinding="{Binding OrderStatusDescription}"/>
<telerik:GridViewDataColumn Header="Patient Name" DataMemberBinding="{Binding PatientName}"/>
But the example is not compiling correctly. The problem is here:
CheckBox Content="{Binding Header}"
The main error listed is: Value does not fall within the expected range.
I'm not sure why this is happening. I'll try to post the rest of the error below. Does anyone else have this working, or have any ideas what's up?
System.InvalidOperationException
An unhandled exception was encountered while trying to render the current silverlight project on the design surface. To diagnose this failure, please try to run the project in a regular browser using the silverlight developer runtime.
at Microsoft.Windows.Design.Platform.SilverlightViewProducer.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs e)
at Microsoft.Expression.Platform.Silverlight.SilverlightPlatformSpecificView.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs args)
at Microsoft.Expression.Platform.Silverlight.Host.SilverlightImageHost.<>c_DisplayClass1.b_0(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
System.ArgumentException
Value does not fall within the expected range.
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(IManagedPeerBase obj, DependencyProperty property, DependencyObject doh)
at MS.Internal.XcpImports.SetValue(IManagedPeerBase doh, DependencyProperty property, Object obj)
at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetEffectiveValue(DependencyProperty property, EffectiveValueEntry& newEntry, Object newValue)
at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)
at System.Windows.Data.BindingExpression.SendDataToTarget()
at System.Windows.Data.BindingExpression.SourceAcquired()
at System.Windows.Data.BindingExpression.System.Windows.IDataContextChangedListener.OnDataContextChanged(Object sender, DataContextChangedEventArgs e)
at System.Windows.Data.BindingExpression.DataContextChanged(Object sender, DataContextChangedEventArgs e)
at System.Windows.DataContextChangedEventHandler.Invoke(Object sender, DataContextChangedEventArgs e)
at System.Windows.FrameworkElement.OnDataContextChanged(DataContextChangedEventArgs e)
at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive)
at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent)
at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent, Byte bCanCreateParent)

VisualCollection throwing out of range exception, bound to Observable collection

So I've got an observable collection bound into an ItemsControl.
When I add items to the collection I get an exception of index out of range from the Visual collection.
<ItemsControl x:Name="ReportPages" ItemsSource="{Binding History}" DockPanel.Dock="Top">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ItemsPresenter HorizontalAlignment="Center"/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding ChildWindows}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Grid Margin="0,10,0,10" >
<ItemsPresenter />
<Border x:Name="ResizeFrame" BorderThickness="4" BorderBrush="LightBlue" Visibility="{Binding Active, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</Grid>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas x:Name="LayoutCanvas" Background="white" ClipToBounds="true"
MouseDown="History_MouseLeftButtonDown" PreviewMouseDown="ClosePanels"
Width="{Binding PageSizeProp.PageWidth}" Height="{Binding PageSizeProp.PageHeight}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
The inner ChildWindows is the collection I'm adding items to. One think of note is that ChildWindows is a ReadOnlyObservableCollection, I'm adding via a method that has access to the Collection it is based on.
I'm at a total loss for why this is happening (and only some times).
edit:
here is the actual stack trace
at System.Windows.Media.VisualCollection.Insert(Int32 index, Visual visual)
at System.Windows.Controls.Panel.addChildren(GeneratorPosition pos, Int32 itemCount)
at System.Windows.Controls.Panel.OnItemsChangedInternal(Object sender, ItemsChangedEventArgs args)
at System.Windows.Controls.Panel.OnItemsChanged(Object sender, ItemsChangedEventArgs args)
at System.Windows.Controls.ItemContainerGenerator.OnItemAdded(Object item, Int32 index)
at System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
at System.Windows.Controls.ItemContainerGenerator.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
at System.Windows.Controls.ItemCollection.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex)
at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
at System.Collections.ObjectModel.ReadOnlyObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
at System.Collections.ObjectModel.ReadOnlyObservableCollection`1.HandleCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
at System.Collections.ObjectModel.Collection`1.Add(T item)
at CalManv4UI.DataHistoryReportPageBase.AddNewChart(ChildWindowSaved cws, Boolean activate) in C:\Users\Joel Barsotti\Documents\Visual Studio 2010\Projects\CalMAN V4\CalMANv4-WPF\CalManv4UI\Workflow\DataHistoryReportPageBase.cs:line 72
I had the same problem and my understanding of it
(credits to https://stackoverflow.com/users/249723/vivien-ruiz for the link)
is simply that you are "bound" to have problems if you modify an ObservableCollection which takes part in an ItemSource binding. I found that inserting at index 0 "solves" my problem, but it could still crash. It shouldn't be modified because it isn't a thread-safe class. A better solution is to act on a copy of the list and assign the copy to the bounded collecion once the operation is completed.
For example:
ObservableCollection<ListViewItem> newList = new ObservableCollection<ListViewItem>(mCurrentList);
...
ListViewItem item = new ListViewItem();
item.Content = image;
newList.Add(item);
...
mPictures = newList;
I had a similar problem, took me months to find out the cause, but found it ^^
Check this site, especially if you modify the list from another thread. You seem to have a race condition, may be this is the same one !

Resources