一种简单的方法是将您的 coboboxitem 信息保存在包装器中,并将这些包装器的集合作为组合框的 itemssource。
public class MyComboboxData
{
public string MyImagePath { get; set; }
public string MyText { get; set; }
}
在您的代码隐藏中:
public ObservableCollection<MyComboboxData> MyData { get; private set; }
public MyViewWithCombobox()
{
InitializeComponent();
this.MyData = new ObservableCollection<MyComboboxData>()
{
new MyComboboxData(){MyImagePath = "ImagePath/Image.bmp", MyText = "MyTextString"},
new MyComboboxData(){MyImagePath = "ImagePath/Image2.bmp", MyText = "MyTextString2"}
};
this.DataContext = this;
}
现在您可以简单地绑定到您想要的所有内容:
<Grid>
<ComboBox Name="comboBox1" ItemsSource="{Binding MyData}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImagePath}"/>
<TextBlock Text="{Binding MyText}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{Binding ElementName=comboBox1, Path=SelectedItem.MyText}"/>
</Grid>
ps: 看看MVVM with viewmodel and binding这些任务很容易实现