以编程方式创建的按钮添加的资源不能正常工作
本文关键字:常工作 工作 不能 资源 方式 编程 创建 按钮 添加 | 更新日期: 2023-09-27 17:51:03
我有一个控件模板在窗口的资源字典:
<ControlTemplate x:Key="ActionButton1" TargetType="Button">
<Grid>
<Image Name="Normal" Source="{DynamicResource EnableIconSource}"/>
<Image Name="MouseOver" Source="{DynamicResource MouseOverIconSource}" Visibility="Hidden"/>
<Image Name="Pressed" Source="{DynamicResource PressedIconSource}" Visibility="Hidden"/>
<Image Name="Disabled" Source="{DynamicResource DisabledIconSource}" Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
...
</ControlTemplate.Triggers>
</ControlTemplate>
当我使用xaml中的按钮时,其中的资源正常工作,图像出现在它们的位置
<Button Name="NewClient"
Click="NewClientClick"
Content="?????????? ??????????"
Template="{DynamicResource ActionButton1}">
<Button.Resources>
<BitmapImage x:Key="EnableIconSource" UriSource="/img/invite_next_normal.png"/>
<BitmapImage x:Key="MouseOverIconSource" UriSource="/img/invite_next_mouse_over.png"/>
<BitmapImage x:Key="PressedIconSource" UriSource="/img/invite_next_pressed.png"/>
<BitmapImage x:Key="DisabledIconSource" UriSource="/img/invite_next_disabled.png"/>
</Button.Resources>
</Button>
但是当我尝试在代码中这样做时图像就会显示为透明的
var toolTip = new StackPanel();
var rslt = new Button {Name = "NewClient"};
rslt.Click += NewClientClick;
rslt.Content = "?????????? ??????????";
rslt.Template = FindResource("ActionButton1") as ControlTemplate;
toolTip.Children.Add(new TextBlock
{
FontWeight = FontWeights.Bold,
Text = toolTipHeader
});
toolTip.Children.Add(new TextBlock
{
Text = toolTipText
});
rslt.ToolTip = toolTip;
var resources = new Dictionary<string, string>
{
{"EnableIconSource", "/img/personal.png"},
{"DisabledIconSource", "/img/personal_gray.png"},
{"OverlayIconSource", "/img/not_come.png"},
});
foreach (var resource in resources)
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(resource.Value, UriKind.RelativeOrAbsolute);
bmp.EndInit();
rslt.Resources.Add(resource.Key, bmp);
}
return rslt;
任何想法?
尝试代码部分中图像的绝对路径。初始路径可能不同,可能没有加载文件。