Windows Phone - DependencyProperties
I'm trying to get a UserControl working in Windows Phone 7. I have a few properties which I'd like to bind to, yet they aren't populated regardless of whether I add them as DependencyProperties or not. The only way I can get them to work is by setting the DataContext instead. The code I've tried is (for one property):
public static readonly DependencyProperty MaximumItemsProperty = DependencyProperty.Register("MaximumItems", typeof(int), typeof(ManageIngredientsControl), new PropertyMetadata(0));
/// <summary>
/// Gets or sets the maximum number of items to match.
/// 开发者_高级运维</summary>
/// <value>The maximum number of items to match.</value>
public int MaximumItems
{
get { return Convert.ToInt32(base.GetValue(MaximumItemsProperty)); }
set { base.SetValue(MaximumItemsProperty, value); }
}
<TextBox Grid.Row="1" Grid.Column="1" x:Name="nudMaxIngredients" Width="120" Text="{Binding MaximumItems,Mode=TwoWay,ElementName=root}" InputScope="Number" />
The root UserControl element is called 'root', but the value isn't populated. The only way to get it half working is by using this:
public int MaximumItems
{
get { return Convert.ToInt32(DataContext) }
set { DataContext = value; }
}
It seems something's interfering with the DataContext, but if I'm binding to DependencyProperties why would it matter?
I'm guessing that your TextBox is inside your UserControl. If so, then ElementName binding has an issue, as described here.
Basically, the name you give the UserControl in it's XAML is overwritten by any name given to it where it's used (i.e. in your Page).
The workaround is to use something like:
<TextBox Grid.Row="1" Grid.Column="1" x:Name="nudMaxIngredients" Width="120" Text="{Binding Parent.MaximumItems,Mode=TwoWay,ElementName=LayoutRoot}" InputScope="Number" />
Where LayoutRoot is the root control inside the UserControl's XAML.
Also, your first approach to the MaximumItems property is correct.
精彩评论