Setting name property of control in code-behind causes errors
My current code is as follows:
MyControl pvc = new MyControl ( );
pvc.SetValue(FrameworkElement.NameProperty, "Control_Name");
try
{
Grid.SetColumn( pvc, c );
Grid.SetRow( pvc, r );
layoutRoot.Children.Add( pvc );
}
catch( Exception excep )
{
System.Windows.MessageBox.Show( excep.ToString( ) );
}
My issue is that I get an exception on the line I try to add the control to the layout (layoutRoot.Children.Add开发者_StackOverflow中文版) and this exception only happens if I tried setting the nameproperty of the control, if I don't it works fine.
The exception is a 'System.ArgumentException: Value does not fal within expected range(...)
All i'm really trying to do is set the Name property of the control in codebehind instead of XAML (using x:Name="name"0
edit: The full exception is:
System.ArgumentException: Value does not fall within the expected range. at MS.Internal.XcpImports.CheckHResult(UInt32 hr) at MS.Internal.XcpImports.Collection_Addvalue[T](PresentationFrameworkCollection'1Collection, CValue value) at MS.Internal.XcpImports.Collection_AddDependencyObject[T](PresentationFrameworkCollection'1 collection, DependencyObject value) at System.Windows.PresentationFrameworlCollection'1.AddDependencyObject(DependencyObject value) at System.Windows.Controls.UIElementCollection.AddInternal(UIElement value) at System.Windows.PresentationFrameworkCollection'1.Add(T value) at Controls.MyControl.CreateLayout()
Turns out the problem was that I was setting the same name multiple times, in hindsight that was a rather dumb thing to do on my part.
精彩评论