【问题标题】:wpf create image buttonwpf 创建图像按钮
【发布时间】:2012-04-21 00:03:30
【问题描述】:

我的控件模板和样式:

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

我不应该放一个吗?
我做错了什么?

【问题讨论】:

  • 您没有设置宽度和高度。根据容器的类型,您需要它才能可见(例如,如果使用堆栈面板,而不是网格)。
  • @RandolfRincón-Fadul 我该如何设置它们?我以为我需要添加一个 contentpresenter 并在那里做,但它不允许我在模板中添加一个?你能给我举个很好的例子吗?
  • @RandolfRincón-Fadul 请看看我的编辑
  • 看我的编辑,我放了一个完整的解决方案。

标签: c# wpf controltemplate


【解决方案1】:

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

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

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");
    }

【讨论】:

  • 我认为我的问题是我指定路径的方式。当我给出完整路径时,它显示了图像..它知道从应用程序根目录中找到图像文件夹吗?来源 =“Images/ok.png” 还是我需要像“..//..//Images//ok.png”一样指定它?
  • 您直接从根目录指定资源(不带 //)。
猜你喜欢
  • 2013-02-16
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
相关资源
最近更新 更多