我需要通过代码修改XAML
元素。我需要在content
“ XAML_ScrollViewer”内用新的content
替换原始的ScrollViewer
。 XAML
代码的简单示例。
<ScrollViewer x:Name="XAML_ScrollViewer">
<ListView x:Name="XAML_ListView">
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:SomeInformation">
<Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollViewer>
为此,我使用以下代码。到目前为止一切都很好。出现新的content
。
C#
//SourceElementParent = XAML_ScrollViewer
//GET PRESENT CONTENT
FrameworkElement ControlOldContent = (SourceElementParent as ContentPresenter).Content as FrameworkElement;
//CREATE NEW GRID
Grid NewParentGrid = new Grid();
//USE NEW GRID AS CONTENT
(SourceElementParent as ContentPresenter).Content = NewParentGrid;
//ADD SOME ELEMENT 01
NewParentGrid.Children.Add(XAMLElement_01);
//ADD SOME ELEMENT 02
NewParentGrid.Children.Add(XAMLElement_02);
//ADD OLD CONTENTS INTO A NEW GRID
NewParentGrid.Children.Add(ControlOldContent );
但是当我需要恢复原始的content
时,我无法做到。以下代码必须在Grid
内部ScrollViewer
创建,但必须保留。
C#
//CLEAR ALL CHILDREN OF THE GRID
((SourceElementParent as ContentPresenter).Content as Grid).Children.Clear();
//ADD OLD CONTENT TO THE GRID
((SourceElementParent as ContentPresenter).Content as Grid).Children.Add(ControlOldContent);
因为我想将控件ScrollViewer
恢复到旧状态(content
,就像进行任何修改之前一样),所以我还需要摆脱之前创建的Grid
。但是如果这样做,我用鼠标调整窗口大小会得到exception
。如果我不调整大小,一切看起来都会很好。
我收到以下异常:
e = {Windows.UI.Xaml.UnhandledExceptionEventArgs} 异常= {“无效的指针\ r \ n \ r \ n无效的指针\ r \ n”}
我尝试使用以下代码还原contents
,但失败。
C#
//CLEAR ALL CHILDREN OF GRID
((SourceElementParent as ContentPresenter).Content as Grid).Children.Clear();
//ADD ORIGINAL CONTENT
(SourceElementParent as ContentPresenter).Content = ControlOldContent;
那么,有什么好的提示可以解决这个问题吗?
答案 0 :(得分:-1)
终于找到了可行的解决方案。 Content
必须恢复为新的ScrollContentPresenter
。因此,ContentPresenter
类型必须完全正确,而我之前没有意识到这一点。
//CLEAR ALL CHILDREN OF GRID
((SourceElementParent as ContentPresenter).Content as Grid).Children.Clear();
//RESTORE SCROLLVIEWER CONTENT.
(SourceElementParent as ScrollContentPresenter).Content = new ScrollContentPresenter() { Content = ControlOldContent };