在这里我创建了一个对象(一个带阴影的椭圆)
public MainPage() { InitializeComponent(); Loaded += new RoutedEventHandler(MainPage_Loaded); } voID MainPage_Loaded(object sender,RoutedEventArgs e) { var element = CreateEllipse(); LayoutRoot.Children.Add(element); } public Ellipse CreateEllipse() { StringBuilder xaml = new StringBuilder(); string ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; xaml.Append("<Ellipse "); xaml.Append(string.Format("xmlns='{0}'",ns)); xaml.Append(" x:name='myellipse'"); //causes the exception xaml.Append(" margin='50 10 50 10'"); xaml.Append(" GrID.Row='0'"); xaml.Append(" Fill='#FD2424FF'"); xaml.Append(" stroke='Black' >"); xaml.Append("<Ellipse.Effect>"); xaml.Append("<DropShadowEffect/>"); xaml.Append(" </Ellipse.Effect>"); xaml.Append(" </Ellipse>"); var ellipse = (Ellipse)XamlReader.Load(xaml.ToString()); return ellipse; }
我想要做的是创建对象后我希望能够使用VisualTreeHelper找到父对象.
public voID button1_Click(object sender,RoutedEventArgs e) { DependencyObject o = myellipse; while ((o = VisualTreeHelper.GetParent(o)) != null) { textBox1.Text = (o.GetType().ToString()); } }
有人能指出我在这样的场景中引用动态创建的对象的正确方向,或者如何以编程方式正确定义x:对象的名称?
谢谢,
解决方法Can anyone point me in the right direction for referencing a dynamically created object in a scenario like this or how to properly define x:name for an object programatically?
您不能使用动态生成的类型直接引用“myellipse”.编译器在编译时将x:name转换为类型 – 因为您在运行时加载它,它将不存在.
相反,您可以创建一个“myellipse”变量,并让您的动态生成例程设置它:
voID MainPage_Loaded(object sender,RoutedEventArgs e){ var element = CreateEllipse(); LayoutRoot.Children.Add(element);}private Ellipse myEllipse; public Ellipse CreateEllipse(){ StringBuilder xaml = new StringBuilder(); string ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; xaml.Append("<Ellipse "); xaml.Append(string.Format("xmlns='{0}'",ns)); xaml.Append(" margin='50 10 50 10'"); xaml.Append(" GrID.Row='0'"); xaml.Append(" Fill='#FD2424FF'"); xaml.Append(" stroke='Black' >"); xaml.Append("<Ellipse.Effect>"); xaml.Append("<DropShadowEffect/>"); xaml.Append(" </Ellipse.Effect>"); xaml.Append(" </Ellipse>"); this.myEllipse = (Ellipse)XamlReader.Load(xaml.ToString()); return this.myEllipse;}
话虽这么说,我建议不要使用这样的字符串构建椭圆.您可以直接创建椭圆类,然后添加效果.在这种情况下,您不需要使用XamlReader来解析字符串.
private Ellipse myEllipse; public Ellipse CreateEllipse(){ this.myEllipse = new Ellipse(); this.myEllipse.Effect = new DropShadowEffect(); GrID.SetRow(this.myEllipse,0); // Set propertIEs as needed return this.myEllipse;}总结
以上是内存溢出为你收集整理的c# – 动态创建xaml对象时接收未声明的前缀全部内容,希望文章能够帮你解决c# – 动态创建xaml对象时接收未声明的前缀所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)