1

我的控件模板和样式:

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

我不应该在里面放一个吗?
我究竟做错了什么 ?

4

1 回答 1

2

您没有设置宽度和高度。根据容器的类型,您需要它才能可见(例如,如果使用 stackpanel)。

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

WPF 三态图像按钮

编辑:

我创建了一个新项目,并在开始窗口中写道:

<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");
    }
于 2012-04-21T00:58:38.297 回答