我想根據依賴關係的財產,控制動態生成不同形狀的模板控件看起來是這樣的:更新UI在UWP模板控件時依賴屬性改變
<Style TargetType="local:ColorShape">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ColorShape">
<ContentControl x:Name="shapeParent">
</ContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
它有形狀的depdency屬性: 公共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();
}
我能數據綁定屬性,和它的作品我第一次創建控件:
<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}" />
但是,如果我在視圖模型修改綁定屬性,即產生INotifyPropertyChange
通知,但不會重新繪製模板控制
我試圖在模板控件的依賴項屬性中添加一個回調函數,我可以看到它使用綁定到屬性的新值(在本例中爲ViewModel.Shape
)刷新依賴項屬性,但它不刷新UI(從不再次調用OnApplyTemplate
)。我試圖手動調用ApplyTemplate
方法,並且事件OnApplyTemplate
不會被觸發。
忽略此...虛假點擊...... –