我可以迭代ContentDialog的控件吗?

时间:2017-12-22 02:31:11

标签: c# uwp

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

因为我想在contentdialog中设置每个控件的Tag Property。

例如,

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

1 个答案:

答案 0 :(得分:0)

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
    }
}