MainWindow关注了用于组合框的xaml
MainWindowViewModel.xaml
<ComboBox Name="CountryComboBox" HorizontalAlignment="Left" Margin="40,170,0,0" VerticalAlignment="Top" Width="220"
ItemsSource="{Binding Countries, Mode=OneWay}"
SelectedValue="{Binding SelectedCountry, Mode=TwoWay}">
</ComboBox>
MainWindowViewModel.cs
private string _SelectedCountry;
public string SelectedCountry
{
get
{
return _SelectedCountry;
}
set
{
_SelectedCountry = value;
OnPropertyChanged("SelectedCountry");
}
}
public List<string> Countries {get; set;}
public MainViewModel()
{
Countries = new List<string>();
var a = "Avganistan";
var b = "Azerbeijan";
Countries.Add(a);
Countries.Add(b);
}
如何将图像添加到此国家的组合框值?
答案 0 :(得分:0)
a)声明一个适当的Country
类,它实现INotifyPropertyChanged
interface并具有string Name
和ImageSource
属性以及一个获取这些输入参数的构造函数。
b)将Countries
属性的定义更新为ObservableCollection<Country>
类型。
c)将这个新课程的项目添加到新的Countries
集合中:
Countries.Add(new Country("Some Country",
"pack://application:,,,/AppName;component/Images/Some Country Image.png"));
Countries.Add(new Country("Other Country",
"pack://application:,,,/AppName;component/Images/Other Country Image.png"));
d)为DataTemplate
课程定义Country
(在Resources
所在的ComboBox
或App.xaml
中的<{1}}中:
<DataTemplate DataType="{x:Type YourPrefix:Country}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" Stretch="None" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
e)最后,只需将数据绑定到集合控件的ItemsSource
属性:
<ComboBox ItemsSource="{Binding Countries}" />