在代码隐藏中设置控件的名称属性会导致错误

时间:2011-06-30 01:28:06

标签: c# silverlight xaml

我目前的代码如下:

           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( ) );
           }

我的问题是我在尝试将控件添加到布局(layoutRoot.Children.Add)的行上出现异常,只有在我尝试设置控件的nameproperty时才会出现此异常,如果我不这样做它工作正常。

异常是'System.ArgumentException:Value在预期范围内没有fal(...)

我真正想做的就是在代码隐藏中设置控件的Name属性而不是XAML(使用x:Name =“name”0

编辑:完整的例外是:

  

System.ArgumentException:值有   不在预期的范围内。在   MS.Internal.XcpImports.CheckHResult(UInt32的   hr)at   MS.Internal.XcpImports.Collection_Addvalue [T](PresentationFrameworkCollection'1Collection,   CValue值)at   MS.Internal.XcpImports.Collection_AddDependencyObject [T](PresentationFrameworkCollection'1   集合,DependencyObject值)at   System.Windows.PresentationFrameworlCollection'1.AddDependencyObject(DependencyObject value)at at   System.Windows.Controls.UIElementCollection.AddInternal(的UIElement   价值)   System.Windows.PresentationFrameworkCollection'1.Add(T   价值)   Controls.MyControl.CreateLayout()

1 个答案:

答案 0 :(得分:0)

原来问题是我多次设置相同的名字,事后看来这对我来说是一件相当愚蠢的事情。