【问题标题】:Can I Iterate the Controls of ContentDialog?我可以迭代 ContentDialog 的控件吗?
【发布时间】:2017-12-22 02:31:10
【问题描述】:

如果可用,我想迭代 contentdialog 的所有控件。

因为我想在 contentdialog 中获取和设置每个控件的 Tag 属性。

例如,

    public ContentDialog MyDialog = new ContentDialog
    {
        Title = "My Title",
        Content = "My Content",
        PrimaryButtonText = "OK",
        SecondaryButtonText = "Cancel",
    };

例如伪代码,

void DeepFirstSearch(ContentDialog IN_pMyDialog, DependencyObject IN_pControl)
{
    foreach (pControl in IN_pMyDialog)
    {
       if ( pControl is TextBlock )
       {
         ...
       }
       else if ( pControl is Button )
       {
         ...
       }

       if (pControl.GetChildCount() > 0)
       {
         DeepFirstSearch(IN_pDialog, pControl)
       }
    }
}

【问题讨论】:

标签: c# uwp


【解决方案1】:

ContentDialog 中没有可视树,因此没有子级。你想遍历它的属性,你可以用反射来做到这一点。

var cd = new ContentDialog();
var cdProps = cd.GetType().GetProperties();
foreach (var propInfo in cdProps)
{
    if (typeof(Button).IsAssignableFrom(propInfo.PropertyType))
    {
        var button = (Button)(cd.GetType().GetProperty(propInfo.Name).GetValue(cd, null));
        // Do stuff with it
    }
    if (typeof(TextBlock).IsAssignableFrom(propInfo.PropertyType))
    {
        var textBlock = (TextBlock)(cd.GetType().GetProperty(propInfo.Name).GetValue(cd, null));
        // Do stuff with it
    }
}

【讨论】:

  • 感谢您的回答,它已解决。我有一个想法,但是那个代码不起作用,所以我修改了一点。
  • public void Reflection(ContentDialog IN_pObject) { var cdProps = IN_pObject.GetType().GetProperties(); foreach (var propInfo in cdProps) { string strTypeName = propInfo.ToString().Split(' ')[0]; if (strTypeName == "System.String" || propInfo.Name == "Title" || propInfo.Name == "Content") { //TODO IN_pObject.GetType().GetProperty(propInfo.Name).SetValue( “去做”); } } }
猜你喜欢
  • 2011-12-22
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 2012-07-12
  • 2011-03-26
相关资源
最近更新 更多