【问题标题】:Issue binding Image Source dependency property问题绑定图像源依赖属性
【发布时间】:2010-04-28 10:04:35
【问题描述】:

我已经为 ImageButton 创建了一个自定义控件

<Style TargetType="{x:Type Button}">
     <Setter Property="Template">
           <Setter.Value>
              <ControlTemplate TargetType="{x:Type Local:ImageButton}">
               <StackPanel Height="Auto" Orientation="Horizontal">
                 <Image Margin="0,0,3,0" Source="{Binding ImageSource}" />
                 <TextBlock Text="{TemplateBinding Content}" /> 
               </StackPanel>
              </ControlTemplate>
           </Setter.Value>
     </Setter>
</Style>

ImageButton 类的样子

public class ImageButton : Button
    {
        public ImageButton() : base() { }

        public ImageSource ImageSource
        {
            get { return base.GetValue(ImageSourceProperty) as ImageSource; }
            set { base.SetValue(ImageSourceProperty, value); }
        }
        public static readonly DependencyProperty ImageSourceProperty =
          DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageButton));
    }

但是我无法将 ImageSource 绑定到图像: (此代码在 UI 文件夹中,图像在资源文件夹中)

  <Local:ImageButton x:Name="buttonBrowse1" Width="100" Margin="10,0,10,0"
 Content="Browse ..." ImageSource="../Resources/BrowseFolder.bmp"/>

但是如果我拍摄一个简单的图像,如果指定了相同的来源,它就会显示出来。 谁能告诉我该怎么办?

【问题讨论】:

    标签: wpf binding custom-controls imagesource


    【解决方案1】:

    您需要将 ControlTemplate 中的 Binding 替换为 TemplateBinding,就像对 Content 属性所做的那样:

    <Image Margin="0,0,3,0" Source="{TemplateBinding ImageSource}" />
    

    此外,您的 DependencyProperty 的定义不正确。该字符串应为ImageSource 而不仅仅是Source

    DependencyProperty.Register("ImageSource", typeof(ImageSource), ...
    

    我不知道这个名称冲突是否/在哪里会导致任何问题,但至少强烈建议使用实际 CLR 属性的确切名称。

    编辑:您还必须将 Style 的 TargetType 更改为您的 ImageButton

    <Style TargetType="{x:Type Local:ImageButton}">
    

    【讨论】:

    • 名称冲突确实会导致问题。
    • 用 TemplateBinding 替换绑定会产生编译时错误,因为无法创建类型为“TemplateBindingExtension”的实例。
    • 但我必须保持 ImageButton 的外观与原始按钮相同。我还能怎么做?
    • 我不知道这是否是一个选项,但你可以让 ImageButton 的模板由一个 Button 组成,其 Content 属性设置为 ControlTemplate 的当前内容,如下所示:&lt;Button&gt;&lt;Button.Content&gt;&lt;StackPanel&gt;...&lt;/StackPanel&gt;&lt;/Button.Content&gt;&lt;/Button&gt; .作为另一种选择,您可以查看 Style.BasedOn 属性。
    • 我尝试用“内容”替换“模板”,简单的字符串替换。你是这个意思吗?但这次它没有显示图像。
    猜你喜欢
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 2010-10-09
    • 2011-01-04
    相关资源
    最近更新 更多