繁体   English   中英

以编程方式创建的按钮添加的资源无法正常工作

[英]Programmatically created button added resources doesn't work properly

我在窗口的资源字典中有一个控制模板:

<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;

有任何想法吗?

在代码部分中尝试图像的绝对路径。 初始路径可能会有所不同,并且可能不会加载文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM