wpf - 问题绑定(bind)图像源依赖属性

标签 wpf binding custom-controls imagesource

我为 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 绑定(bind)到图像,如下所示: (此代码位于 UI 文件夹中,图像位于 Resource 文件夹中)

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

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

最佳答案

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

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

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

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

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

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

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

关于wpf - 问题绑定(bind)图像源依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728449/

相关文章:

java - 具有起始值和最终值的进度组件

c# - 在 Windows 应用程序之间传递对缓冲区的引用

c# - TextBox.Text 绑定(bind)到 ViewModel 的属性

user-interface - BlackBerry - 创建自定义日期字段

c++ - Luabridge:返回 C++ 生命周期托管对象

wpf - 数字向后显示?

ios - UINavigationBar 自定义背景图片

C# 使用反射访问窗口属性

wpf - 在复杂、解耦的 WPF 应用程序上使用 Expression Blend 的策略是什么?

c# - 以线程安全的方式创建新窗口