2014-08-28 57 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