微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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"/>
</Grid>
</UserControl>

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

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

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

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

原文地址:https://www.jb51.cc/javaschema/287189.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐