我想以编程方式更改ListBoxItem的ContentTemplateRoot属性。它包含一个文本块,但我想将其分组到一个网格中并添加一些新元素。
我有自己的课程:
public class MyListboxItemClass : ListBoxItem
{
protected override void OnPointerMoved(PointerRoutedEventArgs e)
{
// here I want to add those new elements as parent of my content...
}
}
我试图简单地更改内容,但它不起作用......
实际上我想将ContentTemplateRoot属性更改为Grid ...
答案 0 :(得分:1)
我已经做到了,它看起来很有效:(它只是为了展示如何做到,不完美,有一些不必要的代码)
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;
}