2015-04-01 37 views
0

如果我有这在我的XAML:将嵌套XAML内容平铺到字符串的最佳方式是什么?

<Button Name="MyButton" Content="Hello" /> 

然后,我可以看到的MyButton.Content.ToString()Hello

但是,如果我有我的XAML是这样的:

<Button Name="MyButton"> 
    <StackPanel> 
     <Label Content="Hello" /> 
    </StackPanel> 
</Button> 

然后突然MyButton.Content.ToString()System.Windows.Control.StackPanel

什么是有效“扁平化”FrameworkElement内容并查看实际文本内容的最佳方式?因此,在第二种情况下,它应该像第一种情况一样返回Hello

+0

要么命名内部标签以便它可以被访问,要么您必须编写一个可以检查每种控件类型的递归解析器。你能解释为什么你需要这个吗?可能有助于寻找其他解决方案。 – kidshaw 2015-04-01 21:08:44

回答

1

递归

string fetchContentString(object o) 
     { 
      if (o == null) 
      { 
       return null; 
      } 

      if(o is string) 
      { 
       return o.ToString(); 
      } 

      if(o is ContentControl) //Button ButtonBase CheckBox ComboBoxItem ContentControl Frame GridViewColumnHeader GroupItem Label ListBoxItem ListViewItem NavigationWindow RadioButton RepeatButton ScrollViewer StatusBarItem ToggleButton ToolTip UserControl Window 
      { 
       var cc = o as ContentControl; 

       if (cc.HasContent) 
       { 
        return fetchContentString(cc.Content); 
       } 
       else 
       { 
        return null; 
       } 

      } 

      if(o is Panel) //Canvas DockPanel Grid TabPanel ToolBarOverflowPanel ToolBarPanel UniformGrid StackPanel VirtualizingPanel VirtualizingPanel WrapPanel 
      { 
       var p = o as Panel; 
       if (p.Children != null) 
       { 
        if (p.Children.Count > 0) 
        { 
         if(p.Children[0] is ContentControl) 
         { 
          return fetchContentString((p.Children[0] as ContentControl).Content); 
         }else 
         { 
          return fetchContentString(p.Children[0]); 
         } 
        } 
       } 
      } 

      //Those are special 
      if(o is TextBoxBase) // TextBox RichTextBox PasswordBox 
      { 
       if(o is TextBox) 
       { 
        return (o as TextBox).Text; 
       } 
       else if(o is RichTextBox) 
       { 
        var rt = o as RichTextBox; 
        if (rt.Document == null) return null; 
        return new TextRange(rt.Document.ContentStart, rt.Document.ContentEnd).Text; 
       } 
       else if(o is PasswordBox) 
       { 
        return (o as PasswordBox).Password; 
       } 
      } 

      return null; 
     } 

给它一个ContentControl中,面板或TextboxBase,它应该给你找到的第一个字符串的内容。

的面板中

其无论第一个孩子导致,在文本框底座的密码/文字/文档属性与https://msdn.microsoft.com/en-us/library/bb613548%28v=vs.110%29.aspx#classes_that_contain_arbitrary_content

一些帮助,我没有测试过深深的只是你所提供的2个样品,但多数民众赞成可能是要走的路。

相关问题