场景:在定义wpf 用户控件的时候,希望使用时设置自定义的属性来改变用户控件里的状态或内容等。
下面直接上实例代码:
用户控件的后台代码,定义依赖属性
public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } public string MyProperty { get { return (string)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata("")); } }
Xaml 代码中绑定依赖属性
<UserControl x:Class="WPFTest.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:myCtl="clr-namespace:WPFTest" d:DesignHeight="300" d:DesignWidth="300" mc:Ignorable="d"> <StackPanel> <TextBlock Text="{Binding RelativeSource={RelativeSource Mode= FindAncestor, AncestorType={x:Type myCtl:MyUserControl}}, Path=MyProperty}" /> </StackPanel> </UserControl>
下面是自定义控件的使用实例:
<Window x:Class="WPFTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WPFTest="clr-namespace:WPFTest" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="MainWindow" Width="525" Height="350" mc:Ignorable="d"> <Grid> <WPFTest:MyUserControl MyProperty="ddd" /> </Grid> </Window>
希望对大家有用!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2017-02-22 基于Jquery的实现回车键Enter切换焦点
2017-02-22 一个事半功倍的c#方法 动态注册按钮事件
2017-02-22 Page_ClientValidate 用法
2017-02-22 防止重复提交 仅提交一次的终极绝杀技
2017-02-22 asp.net正则表达式删除指定的HTML标签的代码
2017-02-22 客户端用JavaScript填充DropDownList控件 服务器端读不到值
2017-02-22 asp.net session丢失的解决方法小结