随机选择资源文件并使用它来显示图像

时间:2016-06-14 15:12:24

标签: wpf vb.net resources resx

我正在使用WPF和VB.net代码。我有一个窗口,顶部有5个团队相关图片的区域显示,我想随机选择。这些图片作为资源文件包含在项目中,我有以下代码来获取与每个团队关联的资源文件名列表,其中有效:

Private function LoadPics(byval TeamID) As List(Of string)
    Dim dictEntry as new DictionaryEntry
    Dim runTimeResourceSet as Object
    Dim teamNick as String=NewGame.TeamDT.Rows(TeamID).Item("TeamNickname")

    runTimeResourceSet=My.Resources.ResourceManager.GetResourceSet(CultureInfo.InvariantCulture,False,True)

    for each dictEntry In runTimeResourceSet          
        if dictEntry.Key.ToString().StartsWith(teamNick) then
            myList.Add(dictEntry.key)
        end if              
    Next dictEntry

    return myList
End function

这将返回一个列表,其中包含该团队每张图片的名称。

然而,这段代码是我陷入困境的地方:

Sub New(TeamID As integer)
    Dim filepath = "pack://application:,,,/Project Files/"
    dim myNum as integer

    ' This call is required by the designer.
    InitializeComponent()   
    ' Add any initialization after the InitializeComponent() call.
    DataContext=MyVM   
    myTeam = TeamID   
    LoadPics(myteam)

    myNum=myRand.NextUInt(0,myList.Count-1)
    MyVM.Image1=New BitmapImage(New Uri(filepath+myList(mynum),UriKind.RelativeOrAbsolute)))
    myList.Removeat(myNum)    
    myNum=myRand.NextUInt(0,myList.Count-1)  
    MyVM.Image2=New BitmapImage(New Uri(filepath+myList(myNum),UriKind.RelativeOrAbsolute))
    myList.RemoveAt(myNum)
    myNum=myRand.NextUInt(0,myList.Count-1)
    MyVM.Image3=New BitmapImage(New Uri(filepath+mylist(myNum),UriKind.RelativeOrAbsolute))
    myList.RemoveAt(myNum)
    myNum=myRand.NextUInt(0,myList.Count-1)
    MyVM.Image4=New BitmapImage(New Uri(filepath+myList(myNum),UriKind.RelativeOrAbsolute)) 
    myList.RemoveAt(myNum)
    myNum=myRand.NextUInt(0,myList.Count-1)
    MyVM.Image5=New BitmapImage(New Uri(filepath+myList(myNum),UriKind.RelativeOrAbsolute))

myList中的字符串抛出系统I / O异常,表示无法找到文件名。但是,如果我只是输入它所使用的字符串的名称,因为它设置为属性。那么问题就变成了如何将myList中的字符串名称视为属性名称而不是字符串?例如,如果图片的名称是“MyTeamPic”并且这是myList中的字符串,则会抛出异常。但是,如果我输入MyTeamPic它可以工作,因为它引用了资源文件中的ReadOnly属性而不是字符串。

或者有一种更简单的方法可以做到这一点我没想到?

1 个答案:

答案 0 :(得分:0)

好的我明白了---

我替换了

MyVM.Image1=New BitmapImage(New Uri(filepath+myList(mynum),UriKind.RelativeOrAbsolute)))

使用

MyVM.Image1=New BitmapImage(New Uri(filepath+ResourceManager.GetObject(myList(myNum),CultureInfo.InvariantCulture).ToString(),UriKind.RelativeOrAbsolute))

它运作正常

相关问题