You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在按下用户控件内置按钮时修改其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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 06:43:32