WPF ListBox的进阶使用(二)
项目中经常使用需要根据搜索条件查询数据,然后用卡片来展示数据。用卡片展示数据时,界面的宽度发生变化,希望显示的卡片数量也跟随变化。WrapPanel虽然也可以实现这个功能,但是将多余的部分都留在行尾,十分不美观,最好是能够将多余的宽度平分在每个ListBoxItem之间,比较美观,也符合项目需求。如下便是我自己实现的Panel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls; namespace WpfDemo
{
public class MyWrapPanel : Panel
{
protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize)
{
Size currentLineSize = new Size();
Size panelSize = new Size(); foreach (UIElement element in base.InternalChildren)
{
element.Measure(availableSize);
Size desiredSize = element.DesiredSize; if (currentLineSize.Width + desiredSize.Width > availableSize.Width)
{
panelSize.Width = Math.Max(currentLineSize.Width, panelSize.Width);
panelSize.Height += currentLineSize.Height;
currentLineSize = desiredSize; if (desiredSize.Width > availableSize.Width)
{
panelSize.Width = Math.Max(desiredSize.Width, panelSize.Width);
panelSize.Height += desiredSize.Height;
currentLineSize = new Size();
}
}
else
{
currentLineSize.Width += desiredSize.Width;
currentLineSize.Height = Math.Max(desiredSize.Height, currentLineSize.Height);
}
} panelSize.Width = Math.Max(currentLineSize.Width, panelSize.Width);
panelSize.Height += currentLineSize.Height; return panelSize;
} protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize)
{
int firstInLine = ;
int lineCount = ; Size currentLineSize = new Size(); double accumulatedHeight = ; UIElementCollection elements = base.InternalChildren;
double interval = 0.0;
for (int i = ; i < elements.Count; i++)
{ Size desiredSize = elements[i].DesiredSize; if (currentLineSize.Width + desiredSize.Width > finalSize.Width) //need to switch to another line
{
interval = (finalSize.Width - currentLineSize.Width) / (i - firstInLine + );
arrangeLine(accumulatedHeight, currentLineSize.Height, firstInLine, i, interval); accumulatedHeight += currentLineSize.Height;
currentLineSize = desiredSize; if (desiredSize.Width > finalSize.Width) //the element is wider then the constraint - give it a separate line
{
arrangeLine(accumulatedHeight, desiredSize.Height, i, ++i, );
accumulatedHeight += desiredSize.Height;
currentLineSize = new Size();
}
firstInLine = i;
lineCount++;
}
else //continue to accumulate a line
{
currentLineSize.Width += desiredSize.Width;
currentLineSize.Height = Math.Max(desiredSize.Height, currentLineSize.Height);
}
} if (firstInLine < elements.Count)
{
if (lineCount == )
{
interval = (finalSize.Width - currentLineSize.Width) / (elements.Count - firstInLine + );
}
arrangeLine(accumulatedHeight, currentLineSize.Height, firstInLine, elements.Count, interval);
} return finalSize;
} private void arrangeLine(double y, double lineHeight, int start, int end, double interval)
{
double x = ;
UIElementCollection children = InternalChildren;
for (int i = start; i < end; i++)
{
x += interval;
UIElement child = children[i];
child.Arrange(new Rect(x, y, child.DesiredSize.Width, lineHeight));
x += child.DesiredSize.Width;
}
}
}
}
接下来,便是将这个MyWrapPanel作为ListBox的ItemsPanelTemplate即可:
<Window x:Class="WpfDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:comm="clr-namespace:WpfDemo.CommonControls;assembly=WpfDemo.CommonControls"
xmlns:local="clr-namespace:WpfDemo"
Title="MainWindow" Height="" Width=""> <Grid>
<ListBox ItemsSource="{Binding DataSource}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
VerticalAlignment="Center" BorderThickness="">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<local:MyWrapPanel IsItemsHost="True"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Green" BorderBrush="Yellow" BorderThickness="">
<TextBlock Text="{Binding CameraName}" Width="" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.Style>
<Style TargetType="{x:Type ListBox}"> </Style>
</ListBox.Style>
</ListBox>
</Grid>
</Window>
界面对应的ViewModel:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading; namespace WpfDemo
{
public class MainWindowVM : NotifyPropertyBase
{
private DispatcherTimer timer;
public MainWindowVM()
{
DataSource = new ObservableCollection<WndViewModel>();
Colums = ;
for(int i =; i < ; ++i)
{
var temp = new WndViewModel()
{
CameraName = string.Format("Camera {0}", ++count),
};
DataSource.Add(temp);
}
//timer = new DispatcherTimer();
//timer.Interval = new TimeSpan(0, 0, 1);
//timer.Tick += timer_Tick;
//timer.Start();
} private int count = ;
void timer_Tick(object sender, EventArgs e)
{
var temp = new WndViewModel()
{
CameraName = string.Format("Camera {0}", ++count),
};
DataSource.Add(temp);
Console.WriteLine(temp.CameraName);
if (count <= )
{
Colums = count;
}
else if (count > )
{
count = ;
DataSource.Clear();
Colums = ;
}
} private int colums;
public int Colums
{
get { return colums; }
set
{
SetProperty(ref colums, value);
}
} private ObservableCollection<WndViewModel> dataSource;
public ObservableCollection<WndViewModel> DataSource
{
get { return dataSource; }
set
{
SetProperty(ref dataSource, value);
}
}
}
}
运行结果:

拉伸后:

WPF ListBox的进阶使用(二)的更多相关文章
- WPF ListBox的进阶使用(一)
公司项目有个需求,UI界面支持动态平均分割界面,想了想便想到用ListBox来实现,用UniformGrid作为ListBox的ItemsPanelTemplate,通过动态改变UniformGrid ...
- WPF 4 DataGrid 控件(进阶篇二)
原文:WPF 4 DataGrid 控件(进阶篇二) 上一篇<WPF 4 DataGrid 控件(进阶篇一)>中我们通过DataGridTemplateColumn 类自定义编辑 ...
- MVVM模式和在WPF中的实现(二)数据绑定
MVVM模式解析和在WPF中的实现(二) 数据绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- 自定义WPF ListBox的选中项样式
首先介绍一种简单地方法:就是通过自定义SystemColors类的参数来自定义WPF ListBox选择颜色的,SystemColors的HighlightBrushKey和HighlightText ...
- Android高手进阶教程(二十八)之---Android ViewPager控件的使用(基于ViewPager的横向相册)!!!
分类: Android高手进阶 Android基础教程 2012-09-14 18:10 29759人阅读 评论(35) 收藏 举报 android相册layoutobjectclassloade ...
- Wireshark入门与进阶系列(二)
摘自http://blog.csdn.net/howeverpf/article/details/40743705 Wireshark入门与进阶系列(二) “君子生非异也,善假于物也”---荀子 本文 ...
- WPF ListBox数据绑定
本文来源 http://wshoufeng1989.blog.163.com/blog/static/202047033201282911633670/ 风随影动的博客 使用数据库AllData , ...
- WPF的消息机制(二)- WPF内部的5个窗口之隐藏消息窗口
目录 WPF的消息机制(一)-让应用程序动起来 WPF的消息机制(二)-WPF内部的5个窗口 (1)隐藏消息窗口 (2)处理激活和关闭的消息的窗口和系统资源通知窗口 (3)用于用户交互的可见窗口 (4 ...
- SpringBoot进阶教程(二十九)整合Redis 发布订阅
SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 实现了 发布/订阅消息范例,发送者 (publishers) 不用编程就可以向特定的接受者发送消息 (subscribers). Ra ...
随机推荐
- OneZero第三周第五次站立会议(2016.4.8)
1. 时间: 15:10--15:25 共计15分钟. 2. 成员: X 夏一鸣 * 组长 (博客:http://www.cnblogs.com/xiaym896/), G 郭又铭 (博客:http ...
- python使用Fabric模块实现自动化运维
简介:Fabric是基于Python实现的SSH命令行工具,简化了SSH的应用程序部署及系统管理任务,它提供了系统基础的操作组件,可以实现本地或远程shell命令,包括:命令执行.文件上传.下载及完整 ...
- 在table中tr的display:block在firefox下显示布局错乱问题
[转自:] http://blog.csdn.net/sd2131512/article/details/4720345 按照常理,对于某一单元行需要显示时,使用:display:block属性,不需 ...
- C++STL 算法
算法部分主要由头文件<algorithm>,<numeric>和<functional>组成. <algorithm>是所有STL头文件中最大的一个,其 ...
- s5-1 网络层引言
网络层要做什么? 源和目的之间的网络有哪些类? 数据报网络 提供无连接的服务 虚电路网络 提供面向连接的服务 网络层的目标:把数据分组一路送到接收机. 网络层利用下层--数据链路层提供的服 ...
- SpringBoot2.0.2 Application调用的三种方式
一.注解 @SpringBootApplication 点开查看源码是由多个注解合成的注解,其中主要的注解有: @SpringBootConfigurati ...
- 第27章:MongoDB-索引--唯一索引
①唯一索引 唯一索引的目的是为了让数据库的某个字段的值唯一,为了确保数据的都是合法的,但是唯一索引在插入数据时会对数据进行检查,一旦重复会抛出异常,效率会比较低,唯一索引只是保证数据库数据唯一的最后一 ...
- js 循环向上滚动
aaaaaaaaaaaaaaaaa最开头 aaaaaaaaaaa 1 aaaaaaaaaaa 2 aaaaaaaaaaa 3 aaaaaaaaaaa 4 aaaaaaaaaaa 5 aaaaaaaaa ...
- C++获取当前进程绝对路径
获取进程的绝对路径(代码同时操作字符串获取了文件目录): 第一种代码: wstring GetProgramDir() { TCHAR exeFullPath[MAX_PATH]; // Full p ...
- C#-VS远程通信
上下文 应用程序内的一套规则.例如使用了begentransaction,就建立了一个规则:再如把synchronization特性应用到某个对象,是多个线程轮流访问这个对象,这也在当前应用产生了一个 ...