且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 使用依赖属性(DependencyProperty) 定义用户控件中的Image Source属性

更新时间:2022-09-22 09:13:23

原文:WPF 使用依赖属性(DependencyProperty) 定义用户控件中的Image Source属性

如果你要自定义一个图片按钮控件,那么如何在主窗体绑定这个控件上图片的Source呢?

我向大家介绍一个用 依赖属性(DependencyProperty) 实现的方法。

关于依赖属性的介绍,请大家参考:http://msdn.microsoft.com/zh-cn/library/ms752914.aspx

首先我们看用户控件中如何定义这个依赖属性:

1.新建一个用户控件,命名为ImageButton

2.在CS定义如下代码:

public partial class ImageButton : UserControl
    {
        public ImageSource imgSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }
        public static readonly DependencyProperty ImageSourceProperty;           
        public ImageButton()
        {
            InitializeComponent();
        }
        static ImageButton()
        {
            var metadata = new FrameworkPropertyMetadata((ImageSource)null);
            ImageSourceProperty = DependencyProperty.RegisterAttached("imgSource", typeof(ImageSource), typeof(ImageButton), metadata);
        }
    }

以上代码,我们定义了控件中,Image 的Source属性。

3.在控件的xaml中,添加一个Image控件

完整代码如下:

<UserControl Name="UC" x:Class="TouchScreen12.Controls.ImageButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"            
             mc:Ignorable="d"
             d:DesignHeight="167" d:DesignWidth="177">
    <Grid x:Name="myGrid" Margin="0">
        <Image x:Name="myImage" Source="{Binding ElementName=UC, Path=imgSource}" Width="Auto" Height="Auto" Stretch="Fill" Margin="0,0,0,0"/>   
    </Grid>
</UserControl>

好了,现在这个基础的图片按钮控件就初步完成了。

在工程的主窗体添加这个控件

<imgBut:ImageButton Height="{Binding bHeight}" HorizontalAlignment="Center" x:Name="image1" VerticalAlignment="Center" Width="{Binding bWidth}" Margin="0" imgSource="{Binding Image1Path}"/>

大家可以把图片的路径直接绑定给这个控件了!