简体   繁体   中英

ListView with horizontal layout and wrap from code behind

I am force to use a ListView/listbox from code behind. In that I have to put borders. I wish they wrapped on a new line when needed

ListView lsv = new ListView
{
    Width = 400,
    Height = 200,
    Background = Brushes.LimeGreen,
};
grdMain.Children.Add(lsv);

for (int iii = 0; iii < 15; iii++)
{
    Border b = new Border() { BorderThickness = new Thickness(3),
    BorderBrush = new SolidColorBrush(Colors.Blue), Width = 50, Height = 50     
};
lsv.Items.Add(b);
lsv.ItemsPanel = (ItemsPanelTemplate)XamlReader.Parse("<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><WrapPanel Orientation=\"Horizontal\" HorizontalAlignment=\"Stretch\"/></ItemsPanelTemplate>");

Now with that the effect is the following: 在此处输入图片说明

instead if I put a fixed width Width=\\"300\\"

lsv.ItemsPanel = (ItemsPanelTemplate)XamlReader.Parse("<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><WrapPanel Orientation=\"Horizontal\" Width=\"300\"/></ItemsPanelTemplate>");

it works properly

在此处输入图片说明

the problem is that I can't put a fixed width for the wrap panel and I want it to extend to fill its parent.

Thank you in advance Patrick

You can try doing the following...

ListView listView = new ListView();
var scrollViewer = Utils.GetDescendantByType(listView, typeof(ScrollViewer)) as ScrollViewer;
scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;

Where you will have a helper method

public static class Utils
{
    public static Visual GetDescendantByType(Visual element, Type type)
    {
        if (element == null)
            return null;

        if (element.GetType() == type)
            return element;

        Visual foundElement = null;
        if (element is FrameworkElement)
            (element as FrameworkElement).ApplyTemplate();

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
        {
            Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
            foundElement = GetDescendantByType(visual, type);
            if (foundElement != null)
                break;
        }
        return foundElement;
    }
}

Note, I have note compiled this code as am on a phone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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