简体   繁体   English

如何在UWP中以编程方式更改ContentTemplateRoot?

[英]How to change ContentTemplateRoot programmatically in uwp?

I would like to change the ListBoxItem's ContentTemplateRoot property programmatically. 我想以编程方式更改ListBoxItem的ContentTemplateRoot属性。 It contains a textblock, but I want to group it into a grid and add a few new elements. 它包含一个文本块,但是我想将其分组为一个网格并添加一些新元素。

I have my own class: 我有自己的课程:

public class MyListboxItemClass : ListBoxItem
{  
      protected override void OnPointerMoved(PointerRoutedEventArgs e)       
      {           
       // here I want to add those new elements as parent of my content...        
      }
}

I tried to simply change the Content, but it doesn't work... 我试图简单地更改内容,但是它不起作用...

Actually I want to change the ContentTemplateRoot property to a Grid... 实际上我想将ContentTemplateRoot属性更改为Grid ...

I have made this, it looks like it works: (it's only to show how can do it, not perfect, has some unnecessary code) 我做了这个,看起来像它的工作原理:(这只是为了展示如何做到这一点,并不完美,有一些不必要的代码)

 private object oldRootContent;

public ListboxGestureHandlerItem()
{
    Loaded += ListboxGestureHandlerItem_Loaded;
    LayoutUpdated += ListboxGestureHandlerItem_LayoutUpdated;
}

private void ListboxGestureHandlerItem_LayoutUpdated(object sender, object e)
{
    if(oldRootContent != null && (ContentTemplateRoot as Grid) != null)
    {
        (ContentTemplateRoot as Grid).Children.Add(oldRootContent as FrameworkElement);
        oldRootContent = null;
    }
}

private void ListboxGestureHandlerItem_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
    oldRootContent = (sender as ListboxGestureHandlerItem).ContentTemplateRoot;

    this.ContentTemplate = Create(typeof(Grid));
}

protected override void OnPointerMoved(PointerRoutedEventArgs e)
{
    base.OnPointerMoved(e);
}

public DataTemplate Create(Type type)
{
    return XamlReader.Load(@"<DataTemplate 
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> 
    <" + type.Name + @"/> 
</DataTemplate>") as DataTemplate;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM