如何在后面的代码中将ItemsPanelTemplate设置为动态创建的Grid
我已经在XAML
定义了这个UserControl
,并希望在我的代码后面动态设置ItemsPanelTemplate
(不像示例中的XAML
):
我尝试过类似的东西
this.Items.ItemsPanel.Template = new Grid();
但悲惨地失败了。 有帮助吗?
背景:我只知道运行时网格列和行的数量。
您需要创建ItemsPanelTemplate
并将其VisualTree
设置为FrameworkElementFactory
(不建议使用)以创建Grid
,或使用XamlReader
来解析指定模板的XAML字符串。
此问题包含两种方法的用法示例(尽管是针对不同的模板属性)。
此问题概述了在运行时操作面板的更简单方法。
你可以通过在后面的代码中创建MannualCode来做你想做的事情:1。创建一个如下的方法,它将返回一个ItemsPanelTemplate
private ItemsPanelTemplate GetItemsPanelTemplate() { string xaml = @" "; return XamlReader.Parse(xaml) as ItemsPanelTemplate; }
-
现在将此模板添加到Listbox ItemsPanel中:
MyListBox.ItemsPanel = GetItemsPanelTemplate();
这对我来说很好。 希望这会有所帮助。
保持编码…. 🙂
如果您仍然需要处理元素,则应采用以下(扩展)代码:
首先,我们需要一个帮助器来获取元素:
// -------------------------------------------------------------------- // This function fetches the WrapPanel from oVisual. private WrapPanel m_FetchWrapPanel (Visual oVisual) { // WrapPanel to be returned WrapPanel oWrapPanel = null; // number of childs of oVisual int iNumberChilds = VisualTreeHelper.GetChildrenCount (oVisual); // and running through the childs int i = 0; while ( ( i < iNumberChilds ) && ( oWrapPanel == null ) ) { // fetching visual Visual oVisualChild = ( VisualTreeHelper.GetChild (oVisual, i) as Visual ); if ( ( oVisualChild is WrapPanel ) is true ) { // found oWrapPanel = ( oVisualChild as WrapPanel ); } else { // checking the childs of oVisualChild oWrapPanel = m_FetchWrapPanel (oVisualChild); }; // checking next child i++; }; // returning WrapPanel return (oWrapPanel); }
现在我们创建Panel(或者其他东西):
// -------------------------------------------------------------------- private void m_SettingTemplate () { // the online doc recommends to parse the template string xaml = @" "; // assigning the template oMyListView.ItemsPanel = ( System.Windows.Markup.XamlReader.Parse (xaml) as ItemsPanelTemplate ); // fetching the WrapPanel WrapPanel oWrapPanel = m_WrapPanelAusVisualHolen (oMyListView); Debug.Assert (oWrapPanel != null); if ( oWrapPanel != null ) { // adjusting the size of the WrapPanel to the ListView Binding oBinding = new Binding ("ActualWidth"); oBinding.Source = oMyListView; oWrapPanel.SetBinding (WrapPanel.MaxWidthProperty, oBinding); }; }