【发布时间】:2017-01-11 11:20:57
【问题描述】:
我在 xaml 中有以下代码 sn-p:
<UserControl x:Class="Ournamespace.OurClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
...
d:DesignHeight="250" d:DesignWidth="774" Loaded="UserControl_Loaded">
....
<Button Grid.Column="0" x:Name="Button_NewMarker" Style="{StaticResource ViewpointFlatButtonStyle}" Width="90" Height="65"
VerticalAlignment="Top" Click="Button_NewMarker_Click" x:FieldModifier="public" Margin="0,0,0,0" Grid.Row="1">
<BitmapImage UriSource="Icons/markers_add_disabled.png" />
</Button>
我尝试通过加载新图像来动态替换按钮上的图像
if( !imgCache.ContainsKey(path) )
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(path, UriKind.Relative);
bi.DownloadFailed += bi_DownloadFailed;
bi.DecodeFailed += bi_DecodeFailed;
bi.EndInit();
imgCache[path] = bi;
}
Button_NewMarker.BeginInit();
Button_NewMarker.Content = imgCache[path];
//Button_NewMarker.Content = oldbmp;
Button_NewMarker.EndInit();
没有发生错误(为此被覆盖的事件) 和 BitmapImage 似乎被替换了 - 但由于某种原因它是灰色的。 图像作为资源添加到项目中,加载的第一个图像似乎正在工作 - 但不是动态替换的。
我也尝试过使用<Image ... > 甚至<Image ... <ImageBitmap - 但它们都不起作用 - 我怀疑这与我们的控件是 UserControl 有关。
我在互联网上看到的 - 有大量关于应该做什么和如何做的建议 - 我现在希望用绝对最少的代码量来完成 - 最好不使用绑定和模板。绑定可以作为手动完成后的第二步。
【问题讨论】:
-
也许你可以尝试从 ViewModel 绑定它?
-
您可以将整个答案发布为答案吗?我宁愿先进行更改而没有约束力,只是为了理解这个概念。如果需要,接下来可以将绑定作为复制数据的高级机制。