How to set ItemsPanelTemplate to a dynamically created Grid in code behind

后端 未结 4 1096
我在风中等你
我在风中等你 2021-01-18 09:20

I\'ve got this UserControl defined in XAML and would like to set the ItemsPanelTemplate dynamically in my code behind class (not in th

4条回答
  •  没有蜡笔的小新
    2021-01-18 09:47

    In case that you still have some work to do with the elements, you should take the following (extended) code:

    First we need a helper in order to get the element:

    // --------------------------------------------------------------------
    // 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);
    }
    

    Now we create the Panel (or something):

    // --------------------------------------------------------------------
    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);
      };
    }
    

提交回复
热议问题