简体   繁体   English

如MSDN所示,将ListBox ItemsSource设置为来自StaticResource的对象

[英]Setting ListBox ItemsSource to an object from StaticResource as shown in MSDN

I was exploring DataTemplate and found Styling and Templating on MSDN. 我正在研究DataTemplate在MSDN上找到了样式和模板 It says - 它说 -

" In this sample application, there is a ListBox control that is bound to a list of photos: 在此示例应用程序中,有一个ListBox控件绑定到照片列表:

<ListBox ItemsSource="{Binding Source={StaticResource MyPhotos}}"
     Background="Silver" Width="600" Margin="10" SelectedIndex="0"/>  

This ListBox currently looks like the following: " 当前,该列表框如下所示:

在此处输入图片说明

//...some stuff about DataTemplate ...// // ...有关DataTemplate一些信息... //

In our sample application, each custom Photo object has a Source property of type string that specifies the file path of the image. 在我们的示例应用程序中,每个自定义Photo对象都有一个类型为string的Source属性,用于指定图像的文件路径。 Currently, the photo objects appear as file paths. 当前,照片对象显示为文件路径。 "

" For the photos to appear as images, you create a DataTemplate as a resource: " 为了使照片显示为图像,您可以创建一个DataTemplate作为资源:

<Window.Resources>
...
<!--DataTemplate to display Photos as images
    instead of text strings of Paths-->
<DataTemplate DataType="{x:Type local:Photo}">
  <Border Margin="3">
    <Image Source="{Binding Source}"/>
  </Border>
</DataTemplate>
...
</Window.Resources>  

OK, fair enough, so I declared the Photo class - 好,很公平,所以我宣布了Photo类-

public class Photo
{
    public string Source { get; set; }
} 

My XAML sense is not very good (it's bad actually). 我的XAML感觉不是很好(实际上是不好的 )。 What I don't get here is the way ItemsSource of the ListBox is set. 我在这里没有得到的是ListBox的ItemsSource设置方式。 As far as my XAML goes, "MyPhotos" here have to be an x:Key to an IEnumerable object of Photo type, something like - 就我的XAML而言,“ MyPhotos”必须是Photo类型的IEnumerable对象的x:Key ,例如-

<Window.Resources>
...
<local:PhotoList x:Key="MyPhotos"/>
...
</Window.Resources>  

But I don't have any idea how the PhotoList class should look like in this case. 但是我不知道在这种情况下PhotoList类应该是什么样子。 So, what the Resource would actually look like that cause the ListBox to be populated with the Source strings of the photos? 那么,什么资源实际上看起来像是导致ListBox填充有照片的Source字符串?

FYI : Implementing things in my own way, my DataTemplate exploration got successful, and though this thing here was not my primary concern, I just want to know what I don't know. 仅供参考:以我自己的方式实现事情,我的DataTemplate探索取得了成功,尽管这不是我的首要任务,但我只想知道我不知道的事情。 Can anyone shed some light? 谁能阐明一些想法?

EDIT in response to the Answer provided by HB : 根据 HB 提供的答案进行编辑

The point of the question is to get the result, as shown in the image, before applying the DataTemplate and to get an idea of the Resource that make that happen. 问题的重点是在应用DataTemplate之前获得结果,如图中所示,并获得实现该目标的Resource的想法。

If I make the PhotoList itself an IEnumerable , like - 如果我将PhotoList本身PhotoList IEnumerable ,例如-

public class PhotoList : List<Photo>
{
    //some property to hold the collection of Photo objects??
}

and instantiate it within the Resource, then to what the ItemsSource actually gets bound? 并在Resource中实例化它,然后将ItemsSource实际绑定什么? How it's gonna work? 如何运作? Sorry I didn't understand. 对不起,我听不懂。 I hope you'll elaborate a bit more on this. 希望您能对此进行详细说明。

So, I went for the DataSourceProvider option. 因此,我选择了DataSourceProvider选项。 But since the Data property has no setter, I tried the following - 但是由于Data属性没有设置器,因此我尝试了以下方法-

public class Photo
{
    public string Source { get; set; }
}

public class PhotoList : DataSourceProvider
{
    private List<Photo> _photos;

    public PhotoList()
    {
        _photos = new List<Photo>
                      {
                          new Photo{ Source = @"D:\AppImage\1.jpg"},
                          new Photo{ Source = @"D:\AppImage\2.jpg"},
                          new Photo{ Source = @"D:\AppImage\3.jpg"},
                          new Photo{ Source = @"D:\AppImage\4.jpg"},
                          new Photo{ Source = @"D:\AppImage\5.jpg"},
                      };
        ((List<Photo>)this.Data).AddRange(_photos);
    }
}  

And definitely I'm doing something wrong. 当然,我做错了。 Because, now i get the Cannot create an instance of "PhotoList" error message while instantiating PhotoList within the Resource - 因为,现在在实例化资源中的PhotoList ,出现了无法创建“ PhotoList”错误消息的实例-

<Window.Resources>
    <local:PhotoList x:Key="MyPhotos"/>
</Window.Resources>  

Please help me out here. 请帮我在这里。

The PhotoList itself either has to be an IEnumerable of Photo objects, or it needs to provide one, this can be done by inheriting from DataSourceProvider and exposing the list that way. PhotoList本身必须是IEnumerable of Photo对象,或者需要提供一个,可以通过从DataSourceProvider继承并以这种方式公开列表来完成。


Edit: Obviously if you just inherit from List<T> nothing will display unless you add items, when i said it should be an IEnumerable i meant an immediate implementation that actually enumerates strings right away. 编辑:显然,如果您只是从List<T>继承,除非添加项目,否则不会显示任何内容,当我说它应该是IEnumerable我的意思是立即实现,实际上立即枚举字符串。 If you just want to create a list in XAML you may as well use x:Array . 如果只想在XAML中创建列表,则最好使用x:Array

Also here would be an example of using the DataSourceProvider : 这也是使用DataSourceProvider的示例:

public class PhotoList : DataSourceProvider
{
    protected override void BeginQuery()
    {
        var files = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures))
                        .Where(f => Path.GetExtension(f) == ".png")
        OnQueryFinished(files);
    }
}

This will populate your list with the paths of PNG-files in the personal "Pictures" folder. 这将使用个人“图片”文件夹中的PNG文件的路径填充列表。

Also you will not get the DataTemplate -less appearance of the example if you use a class like Photo unless you override ToString to return the source URL because by default if there is no DataTemplate it will just display the full name of the class. 此外,如果使用类似Photo的类,则不会获得该示例的DataTemplate -less外观,除非重写ToString以返回源URL,因为默认情况下,如果没有DataTemplate ,它将仅显示该类的全名。


In any case you need Photo objects in your collection for the DataTemplate to apply properly. 无论如何,您都需要在集合中使用Photo对象才能正确应用DataTemplate Also you usually do not have collections directly in XAML but some data object which is the DataContext of the Window / UserControl . 同样,您通常在XAML中没有直接的集合,而是一些数据对象,即Window / UserControlDataContext

 <Window.Resources>
    <ph:PhotoList x:Key="MyPhotos"  Path="D:\Visual Studio Projects\WPF APPLICATIONS\ImageViewer\ImageViewer\Images">      
    </ph:PhotoList>    
 </Window.Resources>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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