all
My application sometimes crashes and throws an exception When I delete multiple items in ListBox.
I delete items through the delete command in MenuItem of ContextMenu.
I can't reproduce this exception, it's very strange.
The log is:
‧ System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Controls.VirtualizingStackPanel.GetMaxChildArrangeLength(IList children, Boolean isHorizontal)
at System.Windows.Controls.VirtualizingStackPanel.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize)
at System.Windows.Controls.ItemsPresenter.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.ScrollContentPresenter.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
at System.Windows.Controls.ScrollViewer.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Border.ArrangeOverride(Size finalSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize)
at System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Border.ArrangeOverride(Size finalSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.Interop.HwndSource.Process_WM_SIZE(UIElement rootUIElement, IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Interop.HwndSource.LayoutFilterMessage(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 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
Xaml is:
<ListBox ItemsSource="{Binding ImgList}" SelectedItem="{Binding SelectedImg}" Style="{StaticResource ListBoxScroll}" SelectionMode="Extended" Background="#FF353535" HorizontalContentAlignment="Stretch" SelectionChanged="ListBox_SelectionChanged" BorderBrush="{x:Null}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" BorderThickness="0">
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete File" Command="{Binding DeleteImageFileCommand}"/>
</ContextMenu>
</ListBox.ContextMenu>
<ListBox.Resources>
<DataTemplate x:Key="ItemTemplate">
<Border Height="117" Width="208" BorderBrush="#FF979797" BorderThickness="1" Margin="21,0,0,18">
<Grid>
<Label x:Name="Lab" Width="40" Height="20" Grid.Column="0" Content="{Binding Converter={StaticResource ItemToIndex}, Mode=OneWay, Path=., RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" FontSize="14" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Left" VerticalAlignment="Top" Padding="0" Panel.ZIndex="1" Background="White" BorderBrush="#FF353535" BorderThickness="1" Foreground="#FF011627" Margin="-1,-1,0,0"/>
<Image Grid.Column="1" Width="208" Source="{Binding SmallImg, Converter={StaticResource MatToBmp}, IsAsync=True}" Stretch="Uniform"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.Resources>
</ListBox>
Does anyone know how this exception is being thrown?
I hope someone can help me, Thanks!
Update: I add the converter code below, and binding is:
<local:FilterIndexConverter x:Key="ItemToIndex"/>
public class FilterIndexConverter : IValueConverter
{
public object Convert(object value, Type TargetType, object parameter, CultureInfo culture)
{
ListBoxItem item = (ListBoxItem)value;
ListBox listBox = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
int index = (listBox.ItemsSource as RangeObservableCollection<ImageInformation>).IndexOf((value as ListBoxItem).Content as ImageInformation);
return index + 1;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
What System.Windows.Controls.VirtualizingStackPanel.GetMaxChildArrangeLength(IList children, Boolean isHorizontal)
Means:
The listbox has a VirtualizingStackPanel which is used to virtualise it's items. To do this it needs to decide what's going to fit in it.
WPF has a measure arrange mechanism which it uses to decide on what space everything needs. It looks at each thing in say a panel and asks what space it would like, then it looks at what constraints there are on it and decides what it can have as a measurement. It then arranges everything. Then renders.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/layout?view=netframeworkdesktop-4.8#LayoutSystem_Overview
GetMaxChildArrangeLength is pretty obviously deciding how many items it will be able to fit in the viewport.
You have this error because when it comes to one of those things it's trying to arrange, it gets null.
You do not seem to be able to reproduce this error.
Any fix is therefore going to have to be somewhat speculative. A guess.
My guess is one or both of your converters are too complicated. Maybe that index converter is being called on something is actually virtualised and doesn't have a container.
It could also / alternatively be your image converter MatToBmp causing this.
I can't see the source to that but I'm guessing it's an expensive process because you made it async.
My suggestion is to make both these do less work. Make them simpler or obviate them.
You can get item index much easier by setting AlternationCount high - to like 10,0000 and bind to AlternationIndex. Add 1.
{Binding
RelativeSource={RelativeSource Mode=TemplatedParent},
Path=(ItemsControl.AlternationIndex)}
Or alternatively expose an index int from your viewmodel and recalculate.
Similarly, give that image a fixed height to cut down on measure arrange in each template.
Reduce the work MatToBmp is doing. Build bitmapsource in advance or something.
Related
I have an ItemsSource with a bound List of objects:
<ItemsControl ItemsSource="{Binding Sprites}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle Fill="Black"
Width="{Binding Width}"
Height="{Binding Height}"/>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<cmd:EventToCommand Command="{Binding MouseDownOnSpriteCommand}"
PassEventArgsToCommand="True"
EventArgsConverter="{StaticResource EventToEventCommandConverter}"
EventArgsConverterParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UIElement}, AncestorLevel=1}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Now as you can see i tried adding a DataTemplate for the bound Items, however this causes the Visual Studio Designer to throw me the following error message:
XamlParseException: Collection property 'System.Windows.Controls.Grid'.'Triggers' is null.
StackTrace:
at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
at System.Windows.FrameworkElement.ApplyTemplate()
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.Canvas.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.UIElement.UpdateLayout()
My Code however compiles perfectly fine and I can run and execute it without any Problems. The issue is that, as long as the DataTemplate Code is uncommented, the Designer only shows me the Error Message.
I know that the DataTemplate is causing the Problem, because when i hardcode the same Grid into the ItemsControl and then use Interactions.Triggers, I can bind the Event and no Error appears in the Designer. (However I can only bind to Commands in the MainViewModel and not to the actual Items List).
So far I have tried to move the Template into a seperate ResourceDictionary, yet this hasn't changed anything.
Also I know that someone had the same problem before. However Im using Visual Studio 2019 and I have already updated to the newest Version and again the Error still appears.
So I haven't found a direct solution but a workaround.
One thing to note is that I defined my Window's DataContext by using
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
And I believe that somehow influenced the error.
And after testing, I have found that if I move the assigment of my DataContext to code behind, the designer doesn't show the error anymore and works fine.
So basically I used
public MainWindow() {
InitializeComponent();
MainViewModel vm = new MainViewModel();
DataContext = vm;
}
as constructor for my code behind.
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>
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.
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'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>