If I have this:
public class BoardCalc : FrameworkElement
{
public BoardCalc()
{
this.Loaded += BoardCalc_Loaded;
}
void BoardCalc_Loaded(object sender, RoutedEventArgs e)
{
Boards = Math.Floor(LengthRequired / 16);
BoardsRequired2 = Math.Floor(LengthRequired / 16);
}
public Double LengthRequired { get; set; }
private Double _Boards;
public Double Boards
{
get
{
return _Boards;
}
set
{
_Boards = value;
}
}
//public Double Boards
//{
// get { return (Double)GetValue(BoardsProperty); }
// set { SetValue(BoardsProperty, value); }
//}
//// Using a DependencyProperty as the backing store for Boards. This enables animation, styling, binding, etc...
//public static readonly DependencyProperty BoardsProperty =
// DependencyProperty.Register("Boards", typeof(Double), typeof(BoardCalc), null);
public Double BoardsRequired2
{
get { return (Double)GetValue(BoardsRequired2Property); }
set { SetValue(BoardsRequired2Property, value); }
}
// Using a DependencyProperty as the backing store for BoardsRequired2. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BoardsRequired2Property =
DependencyProperty.Register("BoardsRequired2", typeof(Double), typeof(BoardCalc), null);
}
And I do this:
<StackPanel xmlns:Boards="clr-namespace:BoardsUtil" >
<Boards:BoardCalc x:Name="boardCalc1"
LengthRequired="5280" />
<TextBlock Text="{Binding ElementName=boardCalc1, Path=Boards}" />
<TextBlock Text="{Binding ElementName=boardCalc1, Path=BoardsRequired2}" />
</StackPanel>
Two Part question:
When I use a dependency property, the Boards value will be calculated at in the designer and show 330 boards. If I use a regular property it will be 0 at design time. At runtime, either one works. Is this something we expect? If so, or if not, can someone explain to me WHY this is, so I can work around it and check to see if the rest of my code is actually working.
Should I be using a dependency property for LengthRequired? If you set a property from XAML, you should use dependency yes? But if you merely BIND to a property from XAML you can use a regular property? Is this the behavior we see here? Is this what we expect? No? Yes? WHY, so I can decide what to do.
The main reason to use dependency properties is to allow the underlying subsystem to provide additional UI/XAML/WPF based functionality, namely:
1) Binding. In this code:
LengthRequired must be a dependency property. You can set LengthRequired like this
and you can do this
but you can't SET LengthRequired using the Binding extension.
2) Animation 3) Styling
Same basic principle. To allow the underlying UI subsystem to animate from 0 to 100 or whatever, or to get the subsystem to pick up Styling and Themes and whatever, it must be a dependency property.
1,2,3. Reasons to use dependency property. For regular properties you can jam in an INotify.