2012-04-21 169 views
1

我的控件模板和样式:WPF创建图像按钮

<ControlTemplate TargetType="{x:Type Button}" x:Key="ImageButtonTemplate"> 
     <Image Source="..//..//images//ok.png" 
          Width="{TemplateBinding Width}" 
          Height="{TemplateBinding Height}"/> 

    </ControlTemplate> 

    <Style TargetType="{x:Type Button}" x:Key="ImageButton"> 
     <Setter Property="Template" Value="{StaticResource ImageButtonTemplate}"/>       
    </Style> 

    <Button Style="{StaticResource ImageButton}" /> 

按钮不可见... 我失去了什么?

编辑:

试图定义面板的高度和宽度,按钮图像仍然不可见.. 一点帮助。

<ControlTemplate TargetType="{x:Type Button}" x:Key="ImageButtonTemplate"> 
     <Grid> 
      <Image Source="..//images//ok.png" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" />    
     </Grid> 
    </ControlTemplate> 

并不是我想要放在那里吗?
我做错了什么?

+0

您没有设置宽度的高度。根据容器的类型,您需要它以便可见(例如,如果使用堆栈面板而不是网格)。 – 2012-04-21 00:08:28

+0

@RandolfRincón-Fadul 我该如何设置它们? 我以为我需要添加一个contentpresenter并在那里做 但它不允许我在模板中添加一个? 你能否介绍我一个很好的例子? – 2012-04-21 00:18:56

+0

@RandolfRincón-Fadul看看我的编辑请 – 2012-04-21 16:23:54

回答

2

您没有设置宽度和高度。根据容器的类型,您需要它以便可见(例如,如果使用堆栈面板)。

在这里你有另一个相关的问题来解释它。

WPF TriState Image Button

编辑:

我创建一个新项目,并启动窗口中写道:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Class="WpfApplication.MainWindow" 
    x:Name="Window" 
    Title="MainWindow" 
    Width="640" Height="480"> 
    <Window.Resources> 
    <ControlTemplate TargetType="{x:Type Button}" x:Key="ImageButtonTemplate"> 
     <Grid> 
      <Image Source="MB_0024_YT2.png" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" />    
     </Grid> 
    </ControlTemplate> 
    <Style TargetType="{x:Type Button}" x:Key="ImageButton"> 
     <Setter Property="Template" Value="{StaticResource ImageButtonTemplate}"/>       
    </Style> 
    </Window.Resources> 
    <Grid x:Name="LayoutRoot"> 
    <Button Style="{StaticResource ImageButton}" Width="120" Height="120" Click="Button_Click" /> 
    </Grid> 
</Window> 

现在,它的工作。按钮它是可见的,并且在事件处理程序中也正在工作。

事件处理程序:

private void Button_Click(object sender, System.Windows.RoutedEventArgs e) 
    { 
     MessageBox.Show("Hello"); 
    } 
+0

我认为我的问题是我指定路径的方式。 当我给完整的路径,它显示图像.. 它会知道从应用程序根目录找到图像文件夹? Source =“Images/ok.png”还是我需要指定它像 “..//////Images//ok.png” ? – 2012-04-21 21:55:49

+0

您可以直接从根目录指定资源(不含//)。 – 2012-04-22 17:34:01