【发布时间】:2016-03-01 19:38:34
【问题描述】:
我想要根据依赖属性动态生成不同形状的模板控件。控件如下所示:
<Style TargetType="local:ColorShape">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ColorShape">
<ContentControl x:Name="shapeParent">
</ContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
它具有形状的依赖属性: 公共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 中的绑定属性,则会生成 INotifyPropertyChange 通知但不会重新绘制模板控件
我尝试在模板控件的依赖属性中添加回调,我可以看到它使用绑定到属性的新值刷新依赖属性(在本例中为ViewModel.Shape),但它不刷新用户界面(不再调用OnApplyTemplate)。我尝试手动调用ApplyTemplate 方法,并且事件OnApplyTemplate 永远不会被触发。
【问题讨论】:
-
忽略这个...误点击...
标签: c# xaml win-universal-app template-control