将图像添加到组合框值

时间:2014-08-28 08:26:20

标签: c# .net wpf xaml

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);      
}

如何将图像添加到此国家的组合框值?

1 个答案:

答案 0 :(得分:0)

a)声明一个适当的Country类,它实现INotifyPropertyChanged interface并具有string NameImageSource属性以及一个获取这些输入参数的构造函数。

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所在的ComboBoxApp.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}" />