2014-08-28 58 views
0

主窗口有组合框下面的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);  
} 

我如何添加图像这个国家的combobox值?

回答

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)定义DataTemplateCountry类(在XAML Resources其中ComboBox会或App.xaml):

<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}" /> 
+0

这是没有必要更换'List'用'ObservableCollection'导致它在ViewModel' – monstr 2014-08-28 09:43:40

+0

的'构造函数初始化,这是没有必要要么执行'INotifyPropertyChanged'接口,但它是很好的做法。 – Sheridan 2014-08-28 09:52:23