2016-03-01 84 views
0

我想根據依賴關係的財產,控制動態生成不同形狀的模板控件看起來是這樣的:更新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不會被觸發。

+0

忽略此...虛假點擊...... –

回答

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(...)第二個參數

+0

這就是它。問題是我在'PropertyChangeCallback'裏面調用'OnApplyTemplate',而不得不直接調用更新形狀的方法,比如'GetShape'等。 – Nekketsu

相關問題