且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF依赖项属性

更新时间:2022-05-09 03:35:23

您的代码中没有依赖项属性。

There isn't a dependency property in your code.

这是一个依赖项属性:

public partial class FillGraph : UserControl
{
    public FillGraph()
    {
        InitializeComponent();
    }

    public float Percentage
    {
        get { return (float)GetValue(PercentageProperty); }
        set { SetValue(PercentageProperty, value); }
    }

    //  Using a DependencyProperty as the backing store for Percentage.  This 
    //  enables animation, styling, binding, etc...
    public static readonly DependencyProperty PercentageProperty =
        DependencyProperty.Register("Percentage", typeof(float), 
                typeof(FillGraph), new PropertyMetadata(0.0f));
}

如Ayyappan Subramanian所建议的, propdp $ Visual Studio中的c $ c>片段将帮助创建样板。请小心传递给 DependencyProperty.Register()的参数,并确保传递给 new PropertyMetadata()$的默认值c $ c>是正确的类型。 0.0f 是浮点数。如果您为 float 属性传递整数 0 ,它将在运行时引发异常。

As Ayyappan Subramanian suggests, the propdp snippet in Visual Studio will help create the boilerplate. Just be careful with the parameters you pass to DependencyProperty.Register(), and make sure the default value you pass to new PropertyMetadata() is the correct type. 0.0f is a float. If you pass integer 0 for a float property, it'll throw an exception at runtime.

此处的常规属性公共浮动百分比是可选的。它就在那里供您使用代码。 XAML绝对不会碰到它(如果您怀疑我,请在getter和setter中设置断点)。这是有关依赖项属性的一部分。

The regular property public float Percentage here is optional. It's just there for your code to use. XAML won't ever touch it at all (put breakpoints in the getter and setter if you doubt me). That's part of what's special about dependency properties.

以下是在用户控件XAML中使用它的方法。注意绑定的 StringFormat 参数。

And here's how to use it in your usercontrol XAML. Note the StringFormat parameter to the binding.

<Grid>
    <TextBlock 
        Text="{Binding Percentage, RelativeSource={RelativeSource AncestorType=UserControl}, StringFormat='Fill Percentage: {0:#.##}%'}" 
        />
</Grid>

注意:如果您的百分比以0到1的范围表示,大于0到100,请使用 p 百分比格式。小数点后两位使用 p2 。我们省略了,因为格式字符串提供了这一点。

Note: If your percentage is expressed in the range 0 to 1 rather than 0 to 100, use the p percent format instead. We'll use p2 for two digits after the decimal point. We omit the % because the format string provides that.

    <TextBlock 
        Text="{Binding Percentage, StringFormat='Fill Percentage: {0:p2}', RelativeSource={RelativeSource AncestorType=UserControl}}" 
        />

假设问题是基于视图模型的 FillPercentage 属性并正确实现 INotifyPropertyChanged

This XAML from your question is fine just as it is, assuming that the viewmodel has a FillPercentage property and correctly implements INotifyPropertyChanged:

<controls:FillGraph x:Name="HydroModel" Percentage="{Binding FillPercentage}" />