您的位置:首页 > 移动开发

WPF: WrapPanel 容器的数据绑定(动态生成控件、遍历)

2011-09-02 11:14 441 查看
问题:

有一些CheckBox需要作为选项添加到页面上,但是数目不定。而为了方便排版,我选择用WrapPanel面板来作为父容器。那现在的问题就是如何把这些控件添加到这个WrapPanel里了。我想到了两个方法,第一个是先得到控件数目,然后再动态生成并加载到这个WrapPanel里,第二个是设置数据绑定。我想第一个是可行的,但是项目中还涉及到其它问题,所以这里就选择第二个了。问题来了,在WrapPanel中并没有可以用来设置绑定并实现动态生成的东西,那要怎么解决了?

办法:

新建一个ItemsControl控件,并为ItemsSource绑定数据源,然后把ItemsControl.ItemsPanel设置为WrapPanel,最后为ItemsControl.ItemTemplate中的CheckBox.Content绑定数据。

eg:

1、创建数据源类型。
public class business
{
public string txt { get; set; }
}


2、设置数据源

public MainWindow()
{
this.InitializeComponent();
List<business> che = new List<business>()
{
new business() { txt = "选项1"},
new business() { txt = "选项2"},
new business() { txt = "选项3"},
new business() { txt = "选项4"},
new business() { txt = "选项5"},
new business() { txt = "选项6"},
new business() { txt = "选项7"}
};
ItemsControl.ItemsSource = che;
}

3、Xaml中

<ItemsControl  x:Name="itemsControl"  Background="#B28BB2F1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Padding="3">
<WrapPanel>
<CheckBox  Content="{Binding txt}"/>
</WrapPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
调试一下就OK了。

下一篇告诉你怎么遍历这个DataTemplate,并判断哪些checkBox被选中了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: