WPF ListBox ComBox应用DataTemplate 绑定数据
<Window.Resources> <DataTemplate x:Key="DefualtTemplate"> <StackPanel Orientation="Horizontal" > <Border Height="10" Width="10" Background="{Binding ColorCode}"/> <TextBlock Text="{Binding ColorCode}"/> </StackPanel> </DataTemplate> </Window.Resources>
定义key为DefualtTemplate的数据模板,使用border元素的背景颜色显示颜色,使用TextBolck显示颜色代码
<StackPanel Grid.Row="0" Orientation="Vertical" VerticalAlignment="Center"> <ComboBox Name="cmb" ItemTemplate="{StaticResource DefualtTemplate}"/> <ListBox x:Name="lbox" ItemTemplate="{StaticResource DefualtTemplate}"/>
</StackPanel>
在Combox 和ListBox中绑定ItemTemplate
var colors = new List<Color>(); colors.Add(new Color() { ColorCode = "#FFB6C1" }); colors.Add(new Color() { ColorCode = "#FFC0CB" }); colors.Add(new Color() { ColorCode = "#DA70D6" }); colors.Add(new Color() { ColorCode = "#EE82EE" }); colors.Add(new Color() { ColorCode = "#FF00FF" }); this.cmb.ItemsSource = colors; this.lbox.ItemsSource = colors;
public class Color { public string ColorCode { get; set; } }
绑定效果
gitee地址:https://gitee.com/houzhifei/wpf-demo.git