如何在WPF中为图像添加依赖项属性?

时间:2010-01-29 12:05:28

标签: c# wpf dependency-properties

如何将名为weight的属性添加到图像中并使用它:?

myImage.weight

(假设我已经在XAML中定义了myImage)

这是我的代码:

public partial class MainWindow : Window
{
    public double Weight
    {
        get
        {
            return (double)GetValue(WeightProperty);
        }
        set
        {
            SetValue(WeightProperty, value);
        }
    }
    public static readonly DependencyProperty WeightProperty = DependencyProperty.Register("Weight", typeof(Double), typeof(Image));


    public MainWindow()
    {
        this.InitializeComponent();
                    myImage.Weight = 2;'

这里最后一行不起作用,因为属性Weight没有附加到myImage。

以下内容在XAML中也不起作用:

<Image x:Name="myImage" Weight="2" />

2 个答案:

答案 0 :(得分:2)

您需要创建附加属性:

public static double GetWeight(DependencyObject obj)
        {
            return (double)obj.GetValue(WeightProperty);
        }

        public static void SetWeight(DependencyObject obj, double value)
        {
            obj.SetValue(WeightProperty, value);
        }

        public static readonly DependencyProperty WeightProperty =
            Dependenc**strong text**yProperty.RegisterAttached("Weight", typeof(double), typeof(MainWindow));

然后您可以在XAML中使用它,如下所示:

<Image x:Name="myImage" MainWindow.Weight="2" />

我通常会将附加属性放在MainWindow以外的其他位置。

然后,您可以通过以下方式访问代码中的属性值:

    double weight = (double)myImage.GetValue(MainWindow.Weight);
    myImage.SetValue(MainWindow.Weight, 123.0);

答案 1 :(得分:0)

我建议只继承Image类并添加新的依赖项属性。

例如

public class MyImage : System.Windows.Controls.Image
{
    public double Weight
    {
        get { return (double)GetValue(WeightProperty); }
        set { SetValue(WeightProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Weight.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty WeightProperty =
        DependencyProperty.Register("Weight", typeof(double), typeof(MyImage), new UIPropertyMetadata(0.0));

}

然后在您的XAML代码中,使用此本地命名空间:

xmlns:local="clr-namespace:[LIBRARYNAME]"

你可以使用:

<local:MyImage Weight="10.0"/>

这有点麻烦,但我认为它给你最大的控制力。