如何在按下用户控件内置按钮时修改其Dependency Property?
WPF用户控件:按钮触发修改依赖属性的实现方案
需求场景
需要实现一个WPF用户控件,满足以下功能:
- 定义一个
double类型的依赖属性Percentage - 在
TextBlock中显示Percentage的数值(保留两位小数) - 按下按钮时,将
Percentage从0平滑过渡到100
完整实现代码
XAML部分
<UserControl x:Class="WpfApp3.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="MyControl"> <StackPanel Orientation="Vertical"> <TextBlock HorizontalAlignment="Center" Text="{Binding ElementName=MyControl, Path=Percentage, StringFormat=N2}" /> <Button Width="100" Height="50"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Pressed"> <Storyboard Storyboard.TargetName="MyControl" Storyboard.TargetProperty="Percentage"> <DoubleAnimation From="0" To="100" Duration="0:0:1" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Button> </StackPanel> </UserControl>
后台C#代码(定义依赖属性)
public partial class MyUserControl : UserControl { public static readonly DependencyProperty PercentageProperty = DependencyProperty.Register("Percentage", typeof(double), typeof(MyUserControl), new PropertyMetadata(0.0)); public double Percentage { get => (double)GetValue(PercentageProperty); set => SetValue(PercentageProperty, value); } public MyUserControl() { InitializeComponent(); } }
实现说明
- 属性绑定:
TextBlock通过ElementName绑定到用户控件自身的Percentage属性,StringFormat=N2确保数值以两位小数格式显示 - 无代码动画触发:利用按钮内置的
Pressed视觉状态,通过DoubleAnimation在1秒内完成Percentage属性的平滑修改,无需额外的按钮点击事件处理代码 - 依赖属性基础:后台必须正确注册
Percentage依赖属性,才能支持XAML中的绑定和动画操作
内容的提问来源于stack exchange,提问作者Heartbane
相关产品推荐
相关产品推荐

