2015-05-28 29 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

問題是,如果我只是用這種方式將這些圖像放在堆棧面板中的按鈕內容上 - 即使沒有絕對路徑,它們也會正常顯示 –

相關問題