繁体   English   中英

依赖项属性更改时,在UWP模板控件中更新UI

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM