2015-05-28 30 views
0

我在窗口的资源字典中的控件模板:编程方式创建的按钮添加的资源不能正常工作

<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,在IT资源正常工作,并且图像出现在他们的地方

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

任何想法?

回答

0

尝试代码部分中图像的绝对路径。最初的路径可能会有所不同,也许文件不会被加载。

+0

问题是,如果我只是用这种方式将这些图像放在堆栈面板中的按钮内容上 - 即使没有绝对路径,它们也会正常显示 –

相关问题