Can a c#.net class be automatically initialized by databinding to one of the properties of the class? - silverlight

I am following a tutorial on http://msdn.microsoft.com/en-us/wp7trainingcourse_usingbingmapslab_topic3#_Toc271039355.
Source code can be found here: http://az12722.vo.msecnd.net/wp7trainingcourse1-4/labs/usingbingmapslab1-1-0/Source.zip. Select the second project called "Ex2-HandlingPushpins"
This tutorial shows how to place pins on a Bing map by long-pressing a location on the map.
In this tutorial there is a class PushpinCatalog, containing a collection of pushpins (Items). Items is bound to a ListBox control like this:
<Popup x:Name="PushpinPopup" IsOpen="False" Canvas.Top="330" Canvas.Left="45" Opacity="0">
<ListBox x:Name="ListBoxPushpinCatalog"
Width="392" Height="56"
Background="{StaticResource ControlBackgroundBrush}"
ItemsSource="{Binding Items}"
SelectionChanged="ListBoxPushpinCatalog_SelectionChanged">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Width="56" Height="56" Source="{Binding Icon}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.DataContext>
<models:PushpinCatalog />
</ListBox.DataContext>
</ListBox>
</Popup>
And the Items collection is initialized in the constructor of the PushpinCatalog.
My question is, when does the constructor of the PushpinCatalog get called? I tried right-clicking it and selecting "Find all references" in visual studio, but there are none.
If I debug, the call stack shows this:
> UsingBingMaps.dll!UsingBingMaps.Models.PushpinCatalog.PushpinCatalog() Line 44 + 0x6 bytes C#
mscorlib.dll!System.Reflection.RuntimeConstructorInfo.InternalInvoke(System.Reflection.RuntimeConstructorInfo rtci, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object parameters, System.Globalization.CultureInfo culture, bool isBinderDefault, System.Reflection.Assembly caller, bool verifyAccess, ref System.Threading.StackCrawlMark stackMark)
mscorlib.dll!System.Reflection.RuntimeConstructorInfo.InternalInvoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture, ref System.Threading.StackCrawlMark stackMark) + 0x114 bytes
mscorlib.dll!System.Reflection.ConstructorInfo.Invoke(object[] parameters) + 0xa bytes
System.Windows.dll!MS.Internal.TypeProxy.GetCreateObjectDelegate.AnonymousMethod__2a() + 0xb bytes
System.Windows.dll!MS.Internal.TypeProxy.CreateInstance(uint customTypeId) + 0x12 bytes
System.Windows.dll!MS.Internal.FrameworkCallbacks.CreateKnownObject(System.IntPtr nativeRootPeer, uint customTypeId, string initializationString, out System.IntPtr nativePeer, uint isCreatedByParser) + 0x7a bytes
[External Code]
System.Windows.dll!MS.Internal.XcpImports.Application_LoadComponentNative(System.IntPtr pContext, System.IntPtr pComponent, uint cUriStringLength, string uriString, uint cXamlStrLength, byte* pXamlStr, uint cAssemblyStrLength, string assemblyStr)
System.Windows.dll!MS.Internal.XcpImports.Application_LoadComponent(MS.Internal.IManagedPeerBase componentAsDO, string resourceLocator, System.IO.UnmanagedMemoryStream stream, uint numBytesToRead, string assemblyString) + 0x39 bytes
System.Windows.dll!System.Windows.Application.LoadComponent(object component, System.Uri resourceLocator) + 0x136 bytes
UsingBingMaps.dll!UsingBingMaps.MainPage.InitializeComponent() Line 90 + 0x11 bytes C#
UsingBingMaps.dll!UsingBingMaps.MainPage.MainPage() Line 51 + 0x6 bytes C#
mscorlib.dll!System.Reflection.RuntimeConstructorInfo.InternalInvoke(System.Reflection.RuntimeConstructorInfo rtci, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object parameters, System.Globalization.CultureInfo culture, bool isBinderDefault, System.Reflection.Assembly caller, bool verifyAccess, ref System.Threading.StackCrawlMark stackMark)
mscorlib.dll!System.Reflection.RuntimeConstructorInfo.InternalInvoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture, ref System.Threading.StackCrawlMark stackMark) + 0x114 bytes
mscorlib.dll!System.Activator.InternalCreateInstance(System.Type type, bool nonPublic, ref System.Threading.StackCrawlMark stackMark) + 0xf0 bytes
mscorlib.dll!System.Activator.CreateInstance(System.Type type) + 0x2 bytes
Microsoft.Phone.dll!System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(System.AsyncCallback userCallback, System.Windows.Navigation.PageResourceContentLoader.PageResourceContentLoaderAsyncResult result) + 0xe6 bytes
Microsoft.Phone.dll!System.Windows.Navigation.PageResourceContentLoader.BeginLoad.AnonymousMethod__0(object args) + 0x11 bytes
mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo rtmi, object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object parameters, System.Globalization.CultureInfo culture, bool isBinderDefault, System.Reflection.Assembly caller, bool verifyAccess, ref System.Threading.StackCrawlMark stackMark)
mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture, ref System.Threading.StackCrawlMark stackMark) + 0x168 bytes
mscorlib.dll!System.Reflection.MethodBase.Invoke(object obj, object[] parameters) + 0xa bytes
mscorlib.dll!System.Delegate.DynamicInvokeOne(object[] args) + 0x98 bytes
mscorlib.dll!System.MulticastDelegate.DynamicInvokeImpl(object[] args) + 0x8 bytes
mscorlib.dll!System.Delegate.DynamicInvoke(object[] args) + 0x2 bytes
System.Windows.dll!System.Windows.Threading.DispatcherOperation.Invoke() + 0xc bytes
System.Windows.dll!System.Windows.Threading.Dispatcher.Dispatch(System.Windows.Threading.DispatcherPriority priority) + 0x83 bytes
System.Windows.dll!System.Windows.Threading.Dispatcher.OnInvoke(object context) + 0x8 bytes
System.Windows.dll!System.Windows.Hosting.CallbackCookie.Invoke(object[] args) + 0x19 bytes
System.Windows.dll!System.Windows.Hosting.DelegateWrapper.InternalInvoke(object[] args) + 0x2 bytes
System.Windows.RuntimeHost.dll!System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(System.IntPtr pHandle, int nParamCount, System.Windows.Hosting.NativeMethods.ScriptParam[] pParams, ref System.Windows.Hosting.NativeMethods.ScriptParam pResult) + 0x5e bytes
[External Code]
I suspect that through databinding of one of the properties of the class, the containing class is somehow automatically initialized, can anyone explain?

The PushpinCatalog class was created during XAML processing.
<ListBox.DataContext>
<models:PushpinCatalog /> - PushpinCatalog instance creation
</ListBox.DataContext>
After it the DataContext property of ListBox has a reference to you PushpinCatalog model instance.

Related

SerialPort read in extension fails on dotnet error

I'm writing an extension that reads serial port data. I'm running on BC14 OnPremis.
Here is what I have. The global variable, running on client side (obviously serioal port is not on the server, with events because I need to receive data somehow.
var
[RunOnClient]
[WithEvents]
Port: DotNet SerialPortA;
The trigger which is called when data on port is available. It is actually fired.
trigger Port::DataReceived(sender: Variant; e: DotNet SerialDataReceivedEventArgs)
var
CurrPort: DotNet SerialPortA;
BarText: DotNet String;
begin
CurrPort := sender;
BarText := CurrPort.ReadLine();
Message(BarText);
end;
In the dotne.al file I have a declaration for SerialPort type. For some reasons it confused name with something else so I had to add a suffix to type alias. So now my type is called SerialPortA.
assembly("System")
{
Version = '4.0.0.0';
Culture = 'neutral';
PublicKeyToken = 'b77a5c561934e089';
type("System.IO.Ports.SerialPort"; "SerialPortA") { }
type("System.IO.Ports.SerialDataReceivedEventArgs"; "SerialDataReceivedEventArgs") { }
type("System.IO.Ports.SerialErrorReceivedEventArgs"; "SerialErrorReceivedEventArgs") { }
}
The problem is that a call to CurrPort.ReadLine() fails with error:
A call to System.Object.ReadLine failed with this message: The type of one or more arguments does not match the method's parameter type.
I tried to use another method Read. The error is the same. It is most probably related to Nav wrapping/unwrapping all dotnet variables to object type, but I don't know what ca I do with thath. Any guess what is going wrong here?
In the event log there is an error description
Server instance: N721
Category: Runtime
ClientSessionId: b6d2f654-0601-46b7-bd70-ae4fa637d422
ClientActivityId: 75ab980f-28d2-4a47-8d50-787c132c854c
ServerSessionUniqueId: cc752b06-1eab-43ed-8976-f1973da11ae5
ServerActivityId: fbc48c73-482c-4f84-87e3-4b3b1765dc5b
EventTime: 10/08/2020 06:29:21
Message ObjectType: System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
MethodName: ReadLine
BindingFlags: Instance, Public, InvokeMethod
ProcessId: 24200
Tag: 000010P
ThreadId: 199
CounterInformation:
And another one
Server instance: N721
Category: Runtime
ClientSessionId: b6d2f654-0601-46b7-bd70-ae4fa637d422
ClientActivityId: 75ab980f-28d2-4a47-8d50-787c132c854c
ServerSessionUniqueId: cc752b06-1eab-43ed-8976-f1973da11ae5
ServerActivityId: fbc48c73-482c-4f84-87e3-4b3b1765dc5b
EventTime: 10/08/2020 06:29:21
Message (NavNCLDotNetInvokeException): This message had personal data removed. The original may still be in transient telemetry. Find it using the transientTelemetryId.
ParentException: NavNCLDotNetInvokeException
A call to System.Object.ReadLine failed with this message: The type of one or more arguments does not match the method's parameter type.
ExceptionStackTrace:
at Microsoft.Dynamics.Nav.Runtime.NavApplicationMethod.InvokeMethod(ITreeObject obj, String methodName, Object[] args, Boolean resolveHandler, Boolean throwOnNotFound)
at Microsoft.Dynamics.Nav.Service.NSField.InvokeEventTriggerInternal(NavSession con, String eventName)
at Microsoft.Dynamics.Nav.Service.NSField.InvokeEventTrigger(NavSession session, String eventName)
at SyncInvokeInvokeEventTrigger(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.RunInTransactionCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.TransientErrorRetryCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.ErrorMappingCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
InnerException:
ParentException: TargetInvocationException
ExceptionStackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Dynamics.Nav.Runtime.NavApplicationMethod.InvokeMethod(ITreeObject obj, String methodName, Object[] args, Boolean resolveHandler, Boolean throwOnNotFound)
InnerException:
RootException: NavNCLDotNetInvokeException
A call to System.Object.ReadLine failed with this message: The type of one or more arguments does not match the method's parameter type.
ExceptionStackTrace:
at Microsoft.Dynamics.Nav.Types.NavAutomationHelper.GetMethodInfo(String methodName, Type objectType, BindingFlags binding, ParameterModifier[] modifier, Object[] arguments, Type[] referenceTypes)
at Microsoft.Dynamics.Nav.Runtime.NavDotNet.Invoke[T](String methodName, UInt32 methodIndex, BindingFlags flags, ParameterModifier modifier, Type[] referenceTypes, Object[] arguments)
at Microsoft.Dynamics.Nav.Runtime.NavDotNet.InvokeMethod[T](Boolean isStatic, String methodName, UInt32 methodIndex, Object[] arguments)
at Microsoft.Dynamics.Nav.BusinessApplication.Page1057905.Porta58a58DataReceived_Scope.OnRun()
at Microsoft.Dynamics.Nav.Runtime.NavMethodScope.Run()
at Microsoft.Dynamics.Nav.BusinessApplication.Page1057905.Porta58a58DataReceived(NavVariant sender, NavDotNet e)
CallerStackTrace:
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.ErrorMappingCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.PushPopCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationTracer.TraceScopeCombinator(Category telemetryCategory, ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass10_0.<PerformanceCounterCombinator>b__0()
at Microsoft.Dynamics.Nav.Runtime.NavPerformanceCounterSetter.UpdatePerformanceCountersWithAverageServiceOperationDuration(Stopwatch stopWatch, Action action)
at Microsoft.Dynamics.Nav.Runtime.NavPerformanceCounterSetter.UpdatePerformanceCountersWithAverageServiceOperationAction(Action action, NavSession session)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.PerformanceCounterCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.InitClientTelemetryIdsCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.TlsClearCombinator(ServiceOperation innerOperation, NSServiceBase serviceInstance, MethodBase syncMethod, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.<>c__DisplayClass28_1.<Combine>b__1(NSServiceBase serviceInstance, Object[] inputs, Object[]& outputs)
at Microsoft.Dynamics.Nav.Service.ServiceOperationInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
at System.ServiceModel.Dispatcher.MessageRpc.Wrapper.Resume(Boolean& alreadyResumedNoLock)
at System.ServiceModel.Dispatcher.ThreadBehavior.ResumeProcessing(IResumeMessageRpc resume)
at Microsoft.Dynamics.Nav.Runtime.NavSynchronizationContext.<>c__DisplayClass1_0.<ClearThreadLocalStorageDelegate>b__0(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
ProcessId: 24200
Tag: 00000HC
ThreadId: 199
CounterInformation:
I don't have a serial port to test with, so this is of the top of my mind.
You probably need to cast the variant to the correct type:
trigger Port::DataReceived(sender: Variant; e: DotNet SerialDataReceivedEventArgs)
var
Type: DotNet Type;
Convert: DotNet Convert;
CurrPort: DotNet SerialPortA;
BarText: DotNet String;
begin
// This check is just best pratice, but not needed in this case as we know sender is a SerialPort.
if not sender.IsDotNet() then
exit;
Type := GetDotNetType(sender);
CurrPort := Convert.ChangeType(sender, Type);
BarText := CurrPort.ReadLine();
Message(BarText);
end;

Npgsql connection to PostgreSql: Array datatype

I am working in Visual Studio 2015 using Visual Basic. I am connecting to a PostgreSql database using Npgsql. There seems to be a problem with the Array Datatype - or hopefully I am doing something wrong. Some of my code:
Dim aWriter As Npgsql.NpgsqlBinaryImporter
Dim Keys() As String
N_Domain = UBound(myKey_Name, 1)
N_Record = UBound(myKey_Name, 2)
ReDim Keys(0 To N_Domain - 1)
aWriter = Connect.BeginBinaryImport _
("COPY ""GAMS Sets"" FROM STDIN (FORMAT BINARY)")
For Rec = 1 To N_Record
For Dom = 1 To N_Domain
Keys(Dom - 1) = myKey_Name(Dom, Rec)
Next Dom
aWriter.StartRow()
aWriter.Write(myCase, NpgsqlDbType.Text)
aWriter.Write(SyId, NpgsqlDbType.Text)
aWriter.Write(Keys, NpgsqlDbType.Array Or NpgsqlDbType.Text)
Next Rec
aWriter.Dispose()
aWriter.Close()
When I run the code I get an error at aWriter.Dispose():
{"42804: wrong element type"}, ErrorCode: -2147467259.
What is wrong? Isn't Text Arrays supported?
Error details:
Npgsql.PostgresException was unhandled
BaseMessage=wrong element type
Code=42804
ErrorCode=-2147467259
File=arrayfuncs.c
HResult=-2147467259
InternalPosition=0
Line=1306
Message=42804: wrong element type
MessageText=wrong element type
Position=0
Routine=array_recv
Severity=ERROR
Source=Npgsql
SqlState=42804
[Where]=COPY GAMS Sets, line 1, column Keys
StackTrace:
at Npgsql.NpgsqlConnector.DoReadMessage(DataRowLoadingMode dataRowLoadingMode, Boolean isPrependedMessage)
at Npgsql.NpgsqlConnector.ReadMessageWithPrepended(DataRowLoadingMode dataRowLoadingMode)
at Npgsql.NpgsqlConnector.ReadExpecting[T]()
at Npgsql.NpgsqlBinaryImporter.Close()
at Npgsql.NpgsqlBinaryImporter.Dispose()
at ConsoleApplication1.Module1.HVL_Write_Set(String myCase, Int32 SyNr, String SyId, Int32 Dimen, String[] myDomain_Name, String[,] myKey_Name) in \\dtu-storage\hela\Documents\Visual Studio 2015\Projects\GDX API 5\GDX API 5\Module1.vb:line 305
at ConsoleApplication1.Module1.Main() in \\dtu-storage\hela\Documents\Visual Studio 2015\Projects\GDX API 5\GDX API 5\Module1.vb:line 638
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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Specified element is already the logical child of another element. Disconnect it first”

i have user control that contain grid and inside it there is expander the problem is when i try to open new window that uses this user control i get an exception " Specified element is already the logical child of another element. Disconnect it first"
here is my code and its work when first windows created
and the exception occur when show the second window
<UserControl x:Class="DiagramDesigner.WindowsUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:s="clr-namespace:DiagramDesigner"
xmlns:c="clr-namespace:DiagramDesigner.Controls"
mc:Ignorable="d"
d:DesignHeight="700" d:DesignWidth="1000">
<UserControl.Resources>
<ContextMenu x:Key="DesignerCanvasContextMenu">
<MenuItem Header="Paste" Command="{x:Static ApplicationCommands.Paste}">
<MenuItem.Icon>
<Image Source="Resources/Images/Paste.png" Width="16"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Select All" Command="{x:Static s:DesignerCanvas.SelectAll}"/>
</ContextMenu>
</UserControl.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- Toolbox -->
<StackPanel Grid.Column="0" Margin="0,0,5,0">
<Expander Header="Flow Chart" Content="{StaticResource FlowChartStencils}" IsExpanded="True" />
</StackPanel>
<!-- GridSplitter -->
<GridSplitter Focusable="False" Width="2" Background="LightGray"
VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
<!-- Designer -->
<GroupBox Header="Diagram" Grid.Column="1" Margin="3,0,0,0">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<s:DesignerCanvas Focusable="true" x:Name="MyDesigner"
Background="{StaticResource WindowBackgroundBrush}"
Margin="10" FocusVisualStyle="{x:Null}"
ContextMenu="{StaticResource DesignerCanvasContextMenu}"/>
</ScrollViewer>
</GroupBox>
</Grid>
</Grid>
</UserControl>
You cannot reuse the same UIElement instance for different parts of the UI. Either remove it from the first and add it to the second one (not recommended but there are some advanced scenarios were it makes sense) or simply create a new one. It's pretty cheap.
I had this error, and I managed to work out exactly why it was occurring using trial and error.
The problem? I was using the following line of XAML in both context menus for a master/detail grid, using the DXGrid from DevExpress.
<dxb:BarItemLinkSeparator />
Once I the issue was fixed, I noticed that the stack trace did actually give a small clue as to which XAML element was causing the error. The 4th line in the stack trace ends with this:
[snip]ILinksHolder.OnLinkAdded(BarItemLinkBase link)
BarItemLinkBase is the base class for BarItemLinkSeparator, which is our clue that removing said XAML will fix the error.
For context, here is the full stack trace:
System.InvalidOperationException: Specified element is already the logical child of another element. Disconnect it first.
at System.Windows.FrameworkContentElement.ChangeLogicalParent(DependencyObject newParent)
at System.Windows.FrameworkElement.AddLogicalChild(Object child)
at DevExpress.Xpf.Bars.PopupMenu.DevExpress.Xpf.Bars.ILinksHolder.OnLinkAdded(BarItemLinkBase link)
at DevExpress.Xpf.Bars.BarItemLinkCollection.UpdateItemLinkOnAddToCollection(BarItemLinkBase itemLink)
at DevExpress.Xpf.Bars.BarItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CustomizablePopupMenuItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
at System.Collections.ObjectModel.Collection`1.Add(T item)
at DevExpress.Xpf.Bars.BarItemLinkBase.DevExpress.Xpf.Bars.IBarManagerControllerAction.Execute()
at DevExpress.Xpf.Bars.BarManagerActionCollection.Execute()
at DevExpress.Xpf.Bars.BarManagerActionContainer.Execute()
at DevExpress.Xpf.Bars.BarManagerController.Execute()
at DevExpress.Xpf.Bars.BarManagerMenuController.Execute()
at DevExpress.Xpf.Grid.DataControlPopupMenu.ExecuteOriginationViewMenuController(Func`2 getMenuController)
at DevExpress.Xpf.Grid.GridCellMenuInfo.ExecuteMenuController()
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CreateItems()
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.RaiseOpening()
at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(Object value)
at DevExpress.Xpf.Bars.PopupMenuBase.OnIsOpenCoerce(Object value)
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.OnIsOpenCoerce(Object value)
at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(DependencyObject d, Object value)
at System.Windows.DependencyObject.ProcessCoerceValue(DependencyProperty dp, PropertyMetadata metadata, EntryIndex& entryIndex, Int32& targetIndex, EffectiveValueEntry& newEntry, EffectiveValueEntry& oldEntry, Object& oldValue, Object baseValue, Object controlValue, CoerceValueCallback coerceValueCallback, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, Boolean skipBaseValueChecks)
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, Object value)
at System.Windows.Controls.Primitives.Popup.set_IsOpen(Boolean value)
at DevExpress.Xpf.Bars.ContextMenuManager.ShowElementContextMenu(Object contextElement, Boolean openingFromKeyboard)
at DevExpress.Xpf.Bars.ContextMenuManager.OpenContextMenu(Object sender, Boolean openingFromKeyboard)
at DevExpress.Xpf.Bars.ContextMenuManager.OnContextMenuOpening(Object sender, ContextMenuEventArgs e)
at System.Windows.Controls.ContextMenuEventArgs.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.Controls.PopupControlService.RaiseContextMenuOpeningEvent(IInputElement source, Double x, Double y, Boolean userInitiated)
at System.Windows.Controls.PopupControlService.ProcessMouseUp(Object sender, MouseButtonEventArgs e)
at System.Windows.Controls.PopupControlService.OnPostProcessInput(Object sender, ProcessInputEventArgs e)
at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
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)
System.InvalidOperationException: Specified element is already the logical child of another element. Disconnect it first.
at System.Windows.FrameworkContentElement.ChangeLogicalParent(DependencyObject newParent)
at System.Windows.FrameworkElement.AddLogicalChild(Object child)
at DevExpress.Xpf.Bars.PopupMenu.DevExpress.Xpf.Bars.ILinksHolder.OnLinkAdded(BarItemLinkBase link)
at DevExpress.Xpf.Bars.BarItemLinkCollection.UpdateItemLinkOnAddToCollection(BarItemLinkBase itemLink)
at DevExpress.Xpf.Bars.BarItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CustomizablePopupMenuItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
at System.Collections.ObjectModel.Collection`1.Add(T item)
at DevExpress.Xpf.Bars.BarItemLinkBase.DevExpress.Xpf.Bars.IBarManagerControllerAction.Execute()
at DevExpress.Xpf.Bars.BarManagerActionCollection.Execute()
at DevExpress.Xpf.Bars.BarManagerActionContainer.Execute()
at DevExpress.Xpf.Bars.BarManagerController.Execute()
at DevExpress.Xpf.Bars.BarManagerMenuController.Execute()
at DevExpress.Xpf.Grid.DataControlPopupMenu.ExecuteOriginationViewMenuController(Func`2 getMenuController)
at DevExpress.Xpf.Grid.GridCellMenuInfo.ExecuteMenuController()
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CreateItems()
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.RaiseOpening()
at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(Object value)
at DevExpress.Xpf.Bars.PopupMenuBase.OnIsOpenCoerce(Object value)
at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.OnIsOpenCoerce(Object value)
at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(DependencyObject d, Object value)
at System.Windows.DependencyObject.ProcessCoerceValue(DependencyProperty dp, PropertyMetadata metadata, EntryIndex& entryIndex, Int32& targetIndex, EffectiveValueEntry& newEntry, EffectiveValueEntry& oldEntry, Object& oldValue, Object baseValue, Object controlValue, CoerceValueCallback coerceValueCallback, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, Boolean skipBaseValueChecks)
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, Object value)
at System.Windows.Controls.Primitives.Popup.set_IsOpen(Boolean value)
at DevExpress.Xpf.Bars.ContextMenuManager.ShowElementContextMenu(Object contextElement, Boolean openingFromKeyboard)
at DevExpress.Xpf.Bars.ContextMenuManager.OpenContextMenu(Object sender, Boolean openingFromKeyboard)
at DevExpress.Xpf.Bars.ContextMenuManager.OnContextMenuOpening(Object sender, ContextMenuEventArgs e)
at System.Windows.Controls.ContextMenuEventArgs.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.Controls.PopupControlService.RaiseContextMenuOpeningEvent(IInputElement source, Double x, Double y, Boolean userInitiated)
at System.Windows.Controls.PopupControlService.ProcessMouseUp(Object sender, MouseButtonEventArgs e)
at System.Windows.Controls.PopupControlService.OnPostProcessInput(Object sender, ProcessInputEventArgs e)
at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
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)

Import values from CSV into SQL Server

I'm in need of importing CSV data from a client computer to a SQL Server which exists elsewhere on the network. I want to do this with PowerShell as I'm trying to become more fluent in using it.
However, when I use an example I've found on the internet I've run into an issue which I don't understand.
For reference I'm using the third example from:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/28/four-easy-ways-to-import-csv-files-to-sql-server-with-powershell.aspx
I've got the information importing into the datatable, however it appears that once the system tries to insert the data into the database I get the following error which is apparently an issue with how my data is getting into my datatable because the at symbol and bracket seem to be causing the issue.
This is the error:
System.Management.Automation.MethodException: Cannot convert argument "0", with value: "System.Object[]", for "WriteToServer" to
type "System.Data.DataRow[]":
"Cannot convert the "#{[Type]=1; [EID]=803; [FirstName]=Bob; [MiddleInit]=; [LastName]=Miller; [HireDate]=03031903; [Rule]=H;
[Rate]=0100; [Status]=1; [Store]=8; [Dept]=04; [Class]=130;
[Badge]=803;}" value of type
"System.Management.Automation.PSCustomObject" to type "System.Data.DataRow"."
---> System.Management.Automation.PSInvalidCastException: Cannot convert
the "#{[Type]=1; [EID]=803; [FirstName]=Bob; [MiddleInit]=;
[LastName]=Miller; [HireDate]=03031903; [Rule]=H; [Rate]=0100;
[Status]=1; [Store]=8; [Dept]=04; [Class]=130; [Badge]=803;}" value of
type "System.Management.Automation.PSCustomObject" to type
"System.Data.DataRow".
at System.Management.Automation.LanguagePrimitives.ConvertTo(Object
valueToConvert, Type resultType, Boolean recursion, IFormatProvider
formatProvider, TypeTable backupTypeTable)
at System.Management.Automation.LanguagePrimitives.ConvertUnrelatedArrays(Object
valueToConvert, Type resultType, Boolean recursion, PSObject
originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
at System.Management.Automation.LanguagePrimitives.ConvertTo(Object
valueToConvert, Type resultType, Boolean recursion, IFormatProvider
formatProvider, TypeTable backupTypeTable)
at System.Management.Automation.Adapter.PropertySetAndMethodArgumentConvertTo(Object
valueToConvert, Type resultType, IFormatProvider formatProvider)
at System.Management.Automation.Adapter.MethodArgumentConvertTo(Object
valueToConvert, Boolean isParameterByRef, Int32 parameterIndex, Type
resultType, IFormatProvider formatProvider)
at System.Management.Automation.Adapter.SetNewArgument(String methodName, Object[] arguments, Object[] newArguments,
ParameterInformation parameter, Int32 index)
--- End of inner exception stack trace ---
at System.Management.Automation.Adapter.SetNewArgument(String methodName, Object[] arguments, Object[] newArguments,
ParameterInformation parameter, Int32 index)
at System.Management.Automation.Adapter.GetMethodArgumentsBase(String
methodName, ParameterInformation[] parameters, Object[] arguments,
Boolean expandParamsOnBest)
at System.Management.Automation.DotNetAdapter.MethodInvokeDotNet(String
methodName, Object target, MethodInformation[] methodInformation,
Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method,
Object[] arguments)
at System.Management.Automation.ParserOps.CallMethod(Token token, Object target, String methodName, Object[] paramArray, Boolean
callStatic, Object valueToSet)
at System.Management.Automation.MethodCallNode.InvokeMethod(Object
target, Object[] arguments, Object value)
at System.Management.Automation.MethodCallNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode
statement, Array input, Pipe outputPipe, ArrayList& resultList,
ExecutionContext context)
Message + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Write-DataTable.PS1

"BindingExpression path error" using ItemsControl and VirtualizingStackPanel

I'm using Silverlight on Windows Phone 7.
Is it normal to get loads of "BindingExpression path error" debug messages when using a VirtualizingStackPanel? I think it is happening because the visual items are temporarily unbound from the data items collection as they are recycled ...
I have an ItemsControl whose ItemsPanel's ItemsPanelTemplate is a VirtualizingStackPanel. It binds to a "Notes" ObservableCollection on my ViewModel.
<ItemsControl x:Name="ListView" ItemsSource="{Binding Notes}"
ItemTemplate="{StaticResource ListDataTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
This is within a UserControl whose DataContext is set to a MainViewModel ViewModel.
The ListDataTemplate contains a Button, which itself contains some text, data-bound to a property of the items in the Notes ObservableCollection:
<DataTemplate x:Key="ListDataTemplate">
<Button>
<Grid>
<TextBlock TextWrapping="Wrap" Text="{Binding Title}">
</Grid>
</Button>
</DataTemplate>
When I run my program it all works fine - only a small number of items in my Notes collection are bound to at any one time. However I get lots of debug errors as I scroll up and down:
System.Windows.Data Error: BindingExpression path error: 'Title' property not found on 'EnWp7.ViewModels.MainViewModel' 'EnWp7.ViewModels.MainViewModel' (HashCode=119211466). BindingExpression: Path='Title' DataItem='EnWp7.ViewModels.MainViewModel' (HashCode=119211466); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'Title' property not found on 'EnWp7.ViewModels.MainViewModel' 'EnWp7.ViewModels.MainViewModel' (HashCode=119211466). BindingExpression: Path='Title' DataItem='EnWp7.ViewModels.MainViewModel' (HashCode=119211466); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'Title' property not found on 'EnWp7.ViewModels.MainViewModel' 'EnWp7.ViewModels.MainViewModel' (HashCode=119211466). BindingExpression: Path='Title' DataItem='EnWp7.ViewModels.MainViewModel' (HashCode=119211466); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
System.Windows.Data Error: BindingExpression path error: 'Title' property not found on 'EnWp7.ViewModels.MainViewModel' 'EnWp7.ViewModels.MainViewModel' (HashCode=119211466). BindingExpression: Path='Title' DataItem='EnWp7.ViewModels.MainViewModel' (HashCode=119211466); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
It is looking for the "Title" property on the main view model (whose Notes property is the ItemsSource) - I think this is normal - it is a transient situation as the visual items are unbound from items in the Notes collection in order to be recycled by assigning them to another item in the collection.
Has anyone else seen this? Am I right that it is normal?
If I create a dummy Title property on my MainViewModel and set a debug breakpoint then I see this stack trace. Note the "UnlinkContainerFromItem":
...!EnWp7.ViewModels.MainViewModel.Title.get() Line 54 C#
mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo rtmi = {System.Reflection.RuntimeMethodInfo}, object obj = {EnWp7.ViewModels.MainViewModel}, System.Reflection.BindingFlags invokeAttr = Default, System.Reflection.Binder binder = null, object parameters = null, System.Globalization.CultureInfo culture = null, bool isBinderDefault = false, System.Reflection.Assembly caller = null, bool verifyAccess = true, ref System.Threading.StackCrawlMark stackMark = LookForMyCaller)
mscorlib.dll!System.Reflection.RuntimeMethodInfo.InternalInvoke(object obj = {EnWp7.ViewModels.MainViewModel}, System.Reflection.BindingFlags invokeAttr = Default, System.Reflection.Binder binder = null, object[] parameters = null, System.Globalization.CultureInfo culture = null, ref System.Threading.StackCrawlMark stackMark = LookForMyCaller) + 0x14e bytes
mscorlib.dll!System.Reflection.RuntimePropertyInfo.InternalGetValue(System.Reflection.PropertyInfo thisProperty = {System.Reflection.RuntimePropertyInfo}, object obj = {EnWp7.ViewModels.MainViewModel}, object[] index = null, ref System.Threading.StackCrawlMark stackMark = LookForMyCaller) + 0x4e bytes
mscorlib.dll!System.Reflection.RuntimePropertyInfo.GetValue(object obj = {EnWp7.ViewModels.MainViewModel}, object[] index = null) + 0x2 bytes
System.Windows.dll!System.Windows.CLRPropertyListener.Value.get() + 0x1b bytes
System.Windows.dll!System.Windows.PropertyAccessPathStep.ConnectToPropertyInSource() + 0x148 bytes
System.Windows.dll!System.Windows.PropertyAccessPathStep.ConnectToProperty() + 0x16 bytes
System.Windows.dll!System.Windows.PropertyAccessPathStep.ReConnect(object newSource = {EnWp7.ViewModels.MainViewModel}) + 0x13 bytes
System.Windows.dll!System.Windows.PropertyPathListener.ReConnect(object source = {EnWp7.ViewModels.MainViewModel}) + 0x10 bytes
System.Windows.dll!System.Windows.Data.BindingExpression.SourceAquired() + 0x11 bytes
System.Windows.dll!System.Windows.Data.BindingExpression.DataContextChanged(object o = {System.Windows.Controls.TextBlock}, System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x26 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x15 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x11 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x18 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x18 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x18 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x18 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x18 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x18 bytes
System.Windows.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) + 0x59 bytes
System.Windows.dll!System.Windows.FrameworkElement.OnPropertyChanged(System.Windows.DependencyProperty dp = {System.Windows.CoreDependencyProperty}) + 0x1d bytes
System.Windows.dll!System.Windows.DependencyObject.RaisePropertyChangeNotifications(System.Windows.DependencyProperty dp = {System.Windows.CoreDependencyProperty}, object newValue = {EnWp7.ViewModels.MainViewModel}, object oldValue = {EnWp7.Store.NoteLocal}) + 0x38 bytes
System.Windows.dll!System.Windows.DependencyObject.ClearValueInternal(System.Windows.DependencyProperty dp = {System.Windows.CoreDependencyProperty}) + 0x138 bytes
System.Windows.dll!System.Windows.DependencyObject.ClearValue(System.Windows.DependencyProperty dp = {System.Windows.CoreDependencyProperty}) + 0x7 bytes
System.Windows.dll!System.Windows.Controls.ItemContainerGenerator.UnlinkContainerFromItem(System.Windows.DependencyObject container = {System.Windows.Controls.ContentPresenter}, object item = {EnWp7.Store.NoteLocal}, bool isRecycling = true) + 0x1f bytes
System.Windows.dll!System.Windows.Controls.ItemContainerGenerator.Remove(System.Windows.Controls.Primitives.GeneratorPosition position = {System.Windows.Controls.Primitives.GeneratorPosition}, int count = 2, bool isRecycling = true) + 0x14a bytes
System.Windows.dll!System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IRecyclingItemContainerGenerator.Recycle(System.Windows.Controls.Primitives.GeneratorPosition position = {System.Windows.Controls.Primitives.GeneratorPosition}, int count = 2) + 0x9 bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.CleanupRange(int startIndex = 0, int count = 2) + 0x20 bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.CleanupContainers(System.Windows.Controls.ItemsControl itemsControl = {System.Windows.Controls.ItemsControl}) + 0x73 bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(System.Windows.Size constraint = {System.Windows.Size}) + 0xe4 bytes
System.Windows.dll!System.Windows.FrameworkElement.MeasureOverride(System.IntPtr nativeTarget = 102509504, float inWidth = 480.0, float inHeight = 499.0, out float outWidth = 0.0, out float outHeight = 0.0) + 0x45 bytes
Thanks,
Damian
I think your assessment of the situation is correct, but it sounds like a bug in the way the VirtualizingStackPanel works. It's not affecting the execution or bindings of your application at the points where you need it, but raising exceptions is a relatively expensive operation and so it would make sense to update the appropriate DataContext accordingly when unlinking the containers.
I think the best place to raise it as a potential bug would be on the App Hub forums
I know this post is pretty old, but a solution without creating the dummy properties is making sure the DataContext of the items can only be of the type you expect.
I do this with the following converter on the root of the data template:
public class SpecificTypeConverter : IValueConverter
{
public string Type { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || value.GetType().FullName == this.Type)
{
return value;
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Add a static resource like this:
<p:PhoneApplicationPage.Resources>
<converters:SpecificTypeConverter x:Key="MustBeItem" Type="My.Namespace.MyListItemViewModel" />
</p:PhoneApplicationPage.Resources>
And in the data template, use the converter:
<DataTemplate>
<StackPanel DataContext="{Binding Converter={StaticResource MustBeItem}}" >
<TextBlock Tekst="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
Now the Name property of the parent will never be checked.

Resources