2014-10-31 48 views
-2

具有下一个XAML代码如何通过c#中的代码更改wpf中的资源?

<Window.Resources > 
    <ImageBrush x:Key="tile" ImageSource="afraid.png" 
       Opacity=" 20" TileMode="Tile" 
       ViewportUnits="Absolute" 
       Viewport=" 0,0,32,32" 
       ></ImageBrush> 
</Window.Resources> 

我想用C#代码来改变形象,在运行时

我有下面的代码要做到这一点,但代码不能正常工作&我不知道原因:

 ImageBrush img = (ImageBrush)this.FindResource("tile"); 
     ImageSourceConverter conv = new ImageSourceConverter(); 
     ImageSource src = (ImageSource)conv.ConvertFromString("mad.png"); 
     img.ImageSource = src; 
+0

它是如何“不工作”? – Default 2014-10-31 13:44:27

+0

http://i.imgur.com/msbdTzB.png – user2714376 2014-10-31 14:20:30

+0

它是'img',为空吗?你在哪里做FindResource? – Default 2014-10-31 14:36:04

回答

0

请参阅this answer

试试这个,从文件创建一个BitmapImage并将其设置为ImageBrush的ImageSource

ImageBrush img = (ImageBrush)this.FindResource("tile"); 

//change the imagesource in runtime, 
img.ImageSource = new BitmapImage(new Uri("mad.png", UriKind.Relative)); 
+0

我尝试鳕鱼,但没有发生 – user2714376 2014-10-31 14:25:01

+0

它会抛出异常?路径是否正确? – kennyzx 2014-10-31 14:34:51

+0

@Default我发现了一个类似的问题,请参阅我答案中的链接。正如它的建议,Uri路径可能是错误的,因此找不到文件,但我不知道如何解决它。 – kennyzx 2014-10-31 16:03:35

相关问题