简体   繁体   中英

Add Items to ComboBox Programmatically

I have been working with WPF all of 2 days, coming from ASP.NET so bear with me!

I am populating a ComboBox with xml filenames from a directory and adding a icon to each item. I have everything working just fine but I am wondering if there is a "better", more "efficient" way of doing this. As I stated, I am just getting started with WPF and I want to go about things the "right" way. My working code is below, can or should I be going about this a different way? Thanks in advance for any pointers!

<ComboBox Height="24" HorizontalAlignment="Left" Margin="153,138,0,0" Name="cmbFiles" VerticalAlignment="Top" Width="200" //>
private void FillSrFileCombo()
{
    string[] dirFiles = Directory.GetFiles(@"D:\TestFiles", "*.xml");

    foreach (string datei in dirFiles)
    {
        string fileName = System.IO.Path.GetFileName(datei);

        System.Windows.Controls.StackPanel stkPanel = new StackPanel();
        stkPanel.Orientation = Orientation.Horizontal;
        cmbFiles.Items.Add(stkPanel);

        System.Windows.Controls.Image cboIcon = new Image();
        BitmapImage bitMap = new BitmapImage();
        bitMap.BeginInit();
        bitMap.UriSource = new Uri(@"tag.jpg", UriKind.Relative);
        bitMap.EndInit();
        cboIcon.Source = bitMap;
        cboIcon.Height = 15;
        stkPanel.Children.Add(cboIcon);

        System.Windows.Controls.TextBlock cboText = new TextBlock();
        cboText.Text = " - " + fileName;
        stkPanel.Children.Add(cboText);
    }
}

I have answered a similar question an hour ago see here :http://stackoverflow.com/questions/9637514/add-usercontrol-to-listbox-wpf.

I will recap the most important parts here based on your example

In the XAML you need to create a "DataTemplate", that is the XAML representation of your file object - in your case an image + file name. You can create this Datatemplate as a resource and assign it to your ComboBox or simply create it in the combobox if you don't plan to reuse it

<ComboBox ItemsSource="{Binding Files}">
  <ComboBox.ItemTemplate>
    <StackPanel>
      <Image Source="{Binding FileImage}" Height="16" Width="16"/>
      <TextBlock Margin="5" Text="{Binding FileName}" />
    </StackPanel>
  </ComboBox.ItemTemplate>
</ComboBox>

In your Codebehind, you need to create a structure that represets the data you want to present in your combobox - let's say a "FileInfo" class. The FileInfo class needs to expose the "FileImage" and "FileName" as properties so you can bind to them (as seen above). Next, you need to create a collection of such objects in the code-behind of the xaml you put your ComboBox in. The collection needs to be an ObservableCollection.

So you would have smth like this:

public class FileInfo
 {
     public ImageSource FileImage { get; set; }
     public string FileName { get; set; }
 }

and then in the MainWindow.xaml.cs

public ObservableCollection Files { get; private set; } public MainWindow() { InitializeComponent(); this.DataContext = this; Files = new ObservableCollection();

foreach (string datei in dirFiles)
{
   var fName = System.IO.Path.GetFileName(datei);
   BitmapImage bitMap = new BitmapImage();
   bitMap.BeginInit();
   bitMap.UriSource = new Uri(@"tag.jpg", UriKind.Relative);
   bitMap.EndInit();
   Files.Add(new FileInfo(){FileName=fName, FileImage = bitMap});
}

}

You will still need to read a lot about why this will work. I recomend reading about DataTemplates DataBinding, ObservableCollection and in the end, read about MVVM, a pattern that ties all this stuff nicely and allows you to harness all the WPF power and decouple yor logic from the UI.

One way that you should consider for WPF/Silverlight/WP7 apps is the MVVM design pattern .

In this instance you would have a view model containing the collection of items for your ComboBox , and you would use a binding expression to set the ItemsSource of the ComboBox . You would then template the ComboBox to display your item images.

查看数据绑定数据模板 ,这里你需要的唯一C#代码就是获取文件(即使你也可以使用类似ObjectDataProvider类的东西在XAML中执行)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM