Combobox与图像项目-WPF

时间:2016-02-14 11:11:11

标签: wpf data-binding combobox

我是WPF上的新手,我想将图像项添加到组合框中,组合框将根据其名称过滤从硬盘读取。

过滤图像名称应该绑定到不同元素的文本属性。

有什么建议吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

ItemTemplate和ItemSource是您需要设置的属性。 ItemTemplate应指向Datatemplate和ItemSource指向字符串集合(图像的路径)。 This链接可以帮助您。

答案 1 :(得分: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;
}