【问题标题】:Update UI in UWP Template Control when dependency property changes依赖属性更改时更新 UWP 模板控件中的 UI
【发布时间】: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


【解决方案1】:

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(...) 处的第二个参数。

【讨论】:

  • 就是这样。问题是我在PropertyChangeCallback 中调用了OnApplyTemplate。相反,我不得不直接调用方法来更新形状,比如GetShape等。
猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多