2010-01-29 75 views
0

如何添加称为重量的属性到图像中并像这样使用它:?如何将依赖项属性添加到WPF中的图像?

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;' 

这里的最后一行不起作用,因为物业重量不附加到myImage。

这也低于不XAML工作:

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

回答

0

我会建议只是继承了图片类,并添加新的依赖项属性。

例如,

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"/> 

这是很麻烦一点点,但我认为它给你最大程度的控制。

+0

我很好奇为什么-1?谁投了票,究竟是什么原因呢? – 2010-01-29 12:21:57

+1

当团队中的其他人使用属性“AspectRatio”创建一个TheirImage类时会发生什么?如果你需要添加一些功能到Panel类,这已经被Grid,DockPanel,StackPanel等子类化了? 这就是为什么组合通常比继承更好的原因,并且WPF使得组合功能非常强大且易于使用附加属性 – 2010-01-29 12:39:55

+0

一个公平点。虽然,我们在有关团队或其他方面的问题上没有听到任何声音。如果你只有一个属性需要在一门课上完成,那么对于这个问题答案是正确的。 – 2010-01-30 00:24:49

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);