How do I add a dependency property to an image in WPF?
How do I add my property called weight to an image and use it like this:?
myImage.weight
(assuming i have already defined myImage in XAML)
here's my code:
public partial class MainWindow : Window
{
public double Weight
{
get
{
return (double)GetValue(WeightProperty);
}
set
{
Se开发者_运维技巧tValue(WeightProperty, value);
}
}
public static readonly DependencyProperty WeightProperty = DependencyProperty.Register("Weight", typeof(Double), typeof(Image));
public MainWindow()
{
this.InitializeComponent();
myImage.Weight = 2;'
here the last line doesn't work because the property Weight does not attach to myImage.
This below also doesn't work in XAML:
<Image x:Name="myImage" Weight="2" />
You need to create an attached property:
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));
You can then use this in the XAML as below:
<Image x:Name="myImage" MainWindow.Weight="2" />
I would generally put the attached property on something other than MainWindow though.
You can then access the value of the property in code through:
double weight = (double)myImage.GetValue(MainWindow.Weight);
myImage.SetValue(MainWindow.Weight, 123.0);
I would recommend just inheriting the Image class and adding your new dependency property.
Eg.
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));
}
Then in your XAML code, with this local namespace:
xmlns:local="clr-namespace:[LIBRARYNAME]"
you can use:
<local:MyImage Weight="10.0"/>
It's a tad cumbersome, but I think it gives you the most control.
精彩评论