如何通过c#中的代码更改wpf中的资源?

如何通过c#中的代码更改wpf中的资源?,c#,wpf,xaml,C#,Wpf,Xaml,拥有下一个XAML代码 <Window.Resources > <ImageBrush x:Key="tile" ImageSource="afraid.png" Opacity=" 20" TileMode="Tile" ViewportUnits="Absolute" Viewport=" 0,0,32,32" ></Im

拥有下一个XAML代码

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

尝试此操作,从文件创建
BitmapImage
,并将其设置为ImageBrush的
ImageSource

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

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

它怎么会“不工作”?是不是
img
为空?你在哪里找资料?我试了一下化学需氧量,但什么也没有happen@Default我发现了一个类似的问题,请参见我答案中的链接。正如它所建议的,Uri路径可能错误,因此找不到该文件,但我不确定如何修复它。需要更多详细信息,例如图像文件的位置。我认为您是对的!
conv.ConvertFromString
的返回值为空。是的,我同意你的观点,在做出正确的回答之前,OP需要提供更多的信息。
ImageBrush  img = (ImageBrush)this.FindResource("tile");

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