您不需要定义画笔。
我会定义一个类来代表你的水果,就像这样:
公共类水果
{
公共串果获取;设置;
公共颜色获取;设置;
公共字符串colorstr get return color.toString();
公共水果(串果、彩色)
{
水果=水果;
颜色=颜色;
}
}
colorclass是system.windows.media.colorclass。当您在xaml中进行绑定时,binding to ahex
string that representative the color works,andcolor.toString()does just that.
所以现在我有一个你的fruitsclass:。
public-partial-class-mainwindow:window
{
公共列表<水果>水果列表获取;设置;
公共主窗口()
{
初始化组件();
水果列表=新列表<水果>()
{
新水果(“苹果”,颜色,红色)
新水果(“梨”,颜色,绿色),
新水果(“葡萄”,颜色,紫色)
}(二)
cboColors.itemssource=结果列表;
}
}
如上图所示,将ComboBox.itemssource设置到我们的列表。
您的组合框
绑定应该如下所示:
<comboBox:name=“cboColors”horizontallight=“center”margin=“0,20,0,0”
VerticalAlignment=“Top”width=“100”height=“22”>
<ComboBox.itemTemplate>
<数据模板>
<网格>
<grid.columndefinitions>
<columnDefinition width=“自动”/>
<列定义/>
</grid.columndefinitions>
<border background=“绑定颜色str”height=“12”width=“12”margin=“2”/>gt;
<textBlock grid.column=“1”margin=“5,0”verticalalightment=“center”text=“绑定水果”/>gt;
</grid>
</datatemplate>
</ComboBox.itemTemplate>
</ComboBox>
最终输出:

编辑
正在获取所选项目。此时,您的comboBox.itemssourceisboundto your水果列表
list.因此,每当用户从下拉列表中选择一个项目时,都会选择一个类型为fruist的对象。
因此,如果要选择项目,例如,可以使用组合框_selectionchanged
event,然后将组合框.selectedItem
转换为type水果
。
private void cbocolors_selectionchanged(object sender,selectionchangedeventargs e)
{
//将所选项目强制转换为类型水果
var selected=(水果)cbocolors.selectedItem;
//在这里,我将为所选水果设置窗口标题以进行说明。
//您可以随意使用。
this.title=选定的.fruit;
}
我认为,深入研究databinding的世界并学习基础知识是个好主意。
thisandthiscould be a good starting point.
这个Color
班级是System.Windows.Media.Color
类。当你装订的时候XAML
,绑定到Hex
表示颜色工作的字符串,以及Color.ToString()
就是这样。
所以现在我有了你的名单Fruits
等级:
public partial class MainWindow : Window
{
public List<Fruits> FruitList { get; set; }
public MainWindow()
{
InitializeComponent();
FruitList = new List<Fruits>()
{
new Fruits("Apple", Colors.Red),
new Fruits("Pear", Colors.Green),
new Fruits("Grape", Colors.Purple)
};
cboColors.ItemsSource = FruitList;
}
}
集合ComboBox.ItemsSource
如上图所示。
还有你的ComboBox
绑定应如下所示:
<ComboBox x:Name="cboColors" HorizontalAlignment="Center" Margin="0,20,0,0"
VerticalAlignment="Top" Width="100" Height="22">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Background="{Binding ColorStr}" Height="12" Width="12" Margin="2"/>
<TextBlock Grid.Column="1" Margin="5,0" VerticalAlignment="Center" Text="{Binding Fruit}"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
最终输出:

编辑
正在获取所选项目。此时,您的ComboBox.items源
是跳跃给你的FruitList
列表。因此,每当用户从下拉列表中选择一个项目时,类型为的对象Fruist
正在选择。
因此,如果要选择项,可以使用ComboBox_SelectionChanged
事件,并将ComboBox.SelectedItem
into类型水果
.
private void CboColors_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Casting the selected item to type Fruits
var selected = (Fruits)cboColors.SelectedItem;
// Here I'm setting window title to the selected fruit to illustrate.
// You can use this however you like.
this.Title = selected.Fruit;
}
我认为对你来说,潜入DataBinding
学习基础知识。
This和this可能是一个很好的起点。