2016-02-14 79 views
0

我是WPF新手,我想添加圖像項目到組合框,它將根據過濾器的名稱從硬盤讀取組合框。Combobox與圖像項目-WWF

對圖像名稱的過濾應該綁定到不同元素的文本屬性。

有什麼建議嗎?

謝謝!

回答

1

這是一個很好的例子來展示MVVM方法。下面的代碼將做的工作:

XAML

<Window x:Class="simplest.MainWindow" 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
       xmlns:local="clr-namespace:simplest" 
       mc:Ignorable="d" 
       Title="MainWindow" Height="350" Width="525"> 
    <Window.DataContext> 
     <local:MainWindowViewModel /> 
    </Window.DataContext> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition/> 
      <ColumnDefinition/> 
     </Grid.ColumnDefinitions> 
     <Grid.RowDefinitions> 
      <RowDefinition /> 
     </Grid.RowDefinitions> 

     <TextBox x:Name="outputFolder" Height="30" Margin="5" Grid.Column="0" Text="{Binding Filter}"/> 
     <ComboBox Height="30" Grid.Column="1" Margin="5" ItemsSource="{Binding Images}"> 
      <ComboBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <Image MaxWidth="64" MaxHeight="64" Source="{Binding}" /> 
         <TextBlock Text="{Binding}"/> 
        </StackPanel> 
       </DataTemplate> 
      </ComboBox.ItemTemplate> 
     </ComboBox> 
    </Grid> 
</Window> 

C#

class MainWindowViewModel : INotifyPropertyChanged 
{ 
    private string _filter; 
    private ObservableCollection<string> _images = new ObservableCollection<string>(); 
    private readonly string _filesSearchPath = "d:\\"; 

    public MainWindowViewModel() 
    { 
     Filter = "*.jpg"; 
    } 


    public string Filter 
    { 
     get 
     { 
      return _filter; 
     } 

     set 
     { 
      _filter = value; 
      OnPropertyChanged(); 

      RefreshImagesCollection(); 
     } 
    } 

    public ObservableCollection<string> Images 
    { 
     get 
     { 
      return _images; 
     } 
    } 

    private void RefreshImagesCollection() 
    { 
     _images.Clear(); 
     foreach (var fileName in Directory.GetFiles(_filesSearchPath, _filter)) 
     { 
      _images.Add(fileName); 
     } 
    } 

    private void OnPropertyChanged([CallerMemberName] string name = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 
1

ItemTemplate和ItemSource是您需要設置的屬性。 ItemTemplate應指向Datatemplate和ItemSource以收集字符串(圖像路徑)。 This鏈接將幫助你。