加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:06:56 所属栏目:百科 来源:网络整理
导读:原文: WPF 使用依赖属性(DependencyProperty) 定义用户控件中的Image Source属性 如果你要自定义一个图片按钮控件,那么如何在主窗体绑定这个控件上图片的Source呢? 我向大家介绍一个用 依赖属性(DependencyProperty) 实现的方法。 关于依赖属性的介绍,请
原文: 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}"/>

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读