【问题标题】:Populate Listbox with images from directory使用目录中的图像填充列表框
【发布时间】:2012-01-22 03:29:57
【问题描述】:

我在编程和 WPF 方面都是新手。我知道这很容易,但到目前为止我没有尝试过任何工作...... 我想用文件夹中的图像填充列表框。我还需要知道如何强制我的列表框允许滚动到一边。到目前为止,我还没有偶然发现任何似乎有效的东西。

这是我的 C# 代码,它将所选文件夹中的文件添加到列表中 基本上我希望列表框用于保存用户选择作为背景的图片的历史记录。

IList<Bitmap> HistoryImages = new List<Bitmap>();

foreach(String imagefile in Directory.GetFiles( @"C:\ProgramData\etc" ))
{
    HistoryImages.Add( new Bitmap( imagefile) );
}

【问题讨论】:

    标签: c# wpf listbox


    【解决方案1】:

    找到对我有用的东西! XAML 代码:

    <ListBox Name="ImageLog" Background="Transparent" IsEnabled="True"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
        ScrollViewer.VerticalScrollBarVisibility="Hidden" 
        ItemsSource="{Binding Path=Image}" BorderThickness="0" 
        SelectionChanged="ImageLog_SelectionChanged_1">
    </ListBox>
    

    C# 代码:

    foreach(string myFile in Directory.GetFiles( @"C:\ProgramData\MyApp" ) )
    {
    System.Windows.Controls.Image myLocalImage = new System.Windows.Controls.Image(); ;
    myLocalImage.Height = 200;
    myLocalImage.Margin = new Thickness( 5 );
    
    
    BitmapImage myImageSource = new BitmapImage();
    myImageSource.BeginInit();
    myImageSource.UriSource = new Uri( @"file:///" + myFile );
    myImageSource.EndInit();
    myLocalImage.Source = myImageSource;
    
    filePath.Add( myFile );
    ImageLog.Items.Add(myLocalImage);
    }
    

    【讨论】:

    • filePath.Add 来自哪里?
    • 这是一个字符串列表,其中填充了我的目标文件夹中每个文件的文件路径 'public List filePath = new List();'
    【解决方案2】:

    这需要data bindingdata templating 的基础知识。 (如果您阅读并理解了所有内容,您应该能够做到。)

    关于滚动,在ListBoxDisabled上设置ScrollViewer.HorizontalScrollBarVisibilityattached property

    【讨论】:

    • 我了解数据绑定和数据模板应该做什么,但我似乎无法让它真正为我工作。我也在尝试对列表框进行数据绑定吗?图片文件夹? C# 代码中包含的列表?另一个随机对象?
    • @Usta 将您的列表框的 Xaml 放入您的问题中并显示您尝试过的内容。鉴于您的问题缺乏信息,HB 的回答很好。
    • @GarryVass 我的代码类似于...我已经删除了大部分代码,因为在我提出问题之前它无法正常工作 =( 'code' 'code' 我也试过添加一个自定义的 clr-namespace 但我也想不通....
    • @Usta,这段代码暴露了理解绑定的根本差距。例如,“路径”不是指您的 C: 驱动器。最好的办法是推迟你的项目并吸收一些理论。
    • 谢谢你告诉我!我不知道我不知道该怎么做!我将在哪里/如何了解如何使用 DataBinding?一旦我完成列表框,项目就会完成。而且我知道它做起来相对简单,我只是对 WPF 足够熟悉,才能真正猜到它应该怎么走....
    猜你喜欢
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多