How to access a Control inside the data template in C# Metro UI in the code behind

后端 未结 3 562
心在旅途
心在旅途 2020-11-30 13:56

I have a MediaElement that resides inside the datatemplate of flipview, i want to access that MediaElement named \"video\" in the code behind so that i can assign properties

3条回答
  •  长情又很酷
    2020-11-30 14:41

    I extended Jerry's solution to a more flexible and better performance solution in getting only desired controls and do not create intermediated Lists during recursive calls.

    You can simply using like that to get the control:

    var myControl = AllChildren(parent, c => c.Name == "xxx").FirstOrDefault();
    

    For that you should include the following AllChildren funcion:

     private List AllChildren(DependencyObject parent, Func query,   List _List = null ) 
        {
            if (_List == null)
                 _List = new List();
    
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var _Child = VisualTreeHelper.GetChild(parent, i);
                if (_Child is Control && query(_Child))
                {
    
                    _List.Add(_Child as Control);
                }
                AllChildren(_Child, query, _List);
            }
            return _List;
        }
    

提交回复
热议问题