![](/img/trans.png)
[英]Dependency Property on a user control not updating the property when bound data changes
[英]Update UI in UWP Template Control when dependency property changes
我希望模板控件根據依賴項屬性動態生成不同的形狀。該控件如下所示:
<Style TargetType="local:ColorShape">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ColorShape">
<ContentControl x:Name="shapeParent">
</ContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
它具有形狀的依賴屬性:public ShapeType
ShapeType
{
get { return (ShapeType)GetValue(ShapeTypeProperty); }
set { SetValue(ShapeTypeProperty, value); }
}
public static readonly DependencyProperty ShapeTypeProperty =
DependencyProperty.Register("ShapeType", typeof(ShapeType), typeof(ColorShape), new PropertyMetadata(ShapeType.Circle));
我在OnApplyTemplate
方法中生成形狀:
protected override void OnApplyTemplate()
{
var shapeParent = (ContentControl)this.GetTemplateChild("shapeParent");
var shape = GetShape(ShapeType);
shapeParent.Content = shape;
base.OnApplyTemplate();
}
我可以使用DataBind屬性,並且在我第一次創建控件時可以使用:
<Controls:ColorShape Grid.Row="1" Width="200" Height="200" Stroke="Black" ShapeType="{x:Bind ViewModel.Shape, Mode=OneWay}" StrokeThickness="5" Fill="{x:Bind ViewModel.Color, Mode=OneWay}" />
但是,如果我修改ViewModel中的bound屬性,則會生成INotifyPropertyChange
通知,但不會重新繪制模板控件
我試圖在模板控件的dependency屬性中添加一個回調,並且可以看到它使用綁定到該屬性的新值刷新了該依賴屬性(在本例中為ViewModel.Shape
),但沒有刷新UI(再也不會調用OnApplyTemplate
)。 我試圖手動調用ApplyTemplate
方法,並且事件OnApplyTemplate
從未觸發過。
生成模板時,僅調用一次OnApplyTemplate
。 僅當您更改控件上的模板時,才會再次調用它。
您需要的是DependencyProperty上的PropertyChangedCallback
:
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0, OnPropertyChanged);
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Do what you need here
}
(您缺少的部分是new PropertyMetadata(...)
的第二個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.