2011-09-25 28 views
1

在我的WPF UserControl中我有這個資源,請觀察Xml示例中的註釋。在DataTemplate中的RotateTransform Angle上綁定不起作用

<UserControl.Resources> 
    <DataTemplate x:Key="AxisXLabelTemplate"> 
     <ContentPresenter Content="{Binding Path=Content}"> 
      <ContentPresenter.LayoutTransform> 
       <RotateTransform Angle="{Binding XAxisLabelRotation, UpdateSourceTrigger=PropertyChanged}" /> <!-- This does not work --> 
       <!-- <RotateTransform Angle="-90" /> This works --> 
      </ContentPresenter.LayoutTransform> 
     </ContentPresenter> 
    </DataTemplate> 
</UserControl.Resources> 

在我已依賴項屬性定義爲代碼如下:

class MyChart: INotifyPropertyChanged 
{ 
     public static readonly DependencyProperty XAxisLabelRotationProperty = 
      DependencyProperty.Register("XAxisLabelRotation", typeof(RotateTransform), typeof(BarChart), 
       new FrameworkPropertyMetadata((RotateTransform)new RotateTransform(-90.0))); 

     public RotateTransform XAxisLabelRotation 
     { 
      get { return (RotateTransform)GetValue(XAxisLabelRotationProperty); } 
      set { SetValue(XAxisLabelRotationProperty, value); } 
     } 
... 
} 

的AxisXLabelTemplate DataTemplate中被分配給一個元素更遠下面如下:

<chart:AxisLabel ElementTemplate="{StaticResource AxisXLabelTemplate}"/> 

的問題是當我使用Angle的未綁定值並將其硬編碼爲-90時,它的效果非常好,當我嘗試使用XAxisLabelRotation的綁定值時,它不會。

任何人都可以請幫忙嗎?

+0

和你尋找任何綁定錯誤(輸出窗口)? –

回答

3

我重新創建了類似的設置,因爲它並不適合我。奇怪的是沒有綁定錯誤。我也做了relativesource綁定,並沒有奏效。

雖然如果我綁定工具提示

<ContentPresenter ToolTip="{Binding XAxisLabelRotation, 
             RelativeSource={RelativeSource 
              AncestorType={x:Type ContentControl}}, 
              UpdateSourceTrigger=PropertyChanged}" ..> 

顯示工具提示我。所以我改變了旋轉變換,

<RotateTransform Angle="{Binding XAxisLabelRotation, 
             RelativeSource={RelativeSource 
              AncestorType={x:Type ContentControl}}, 
              UpdateSourceTrigger=PropertyChanged}" ..> 

但仍然沒有工作的轉換。仍然沒有綁定錯誤。

然後我介紹了一個虛擬的轉換器...

public class AngleConverter : IValueConverter 
{ 
    public object Convert(...) 
    { 
     return value; 
    } 
    .... 
} 

<RotateTransform Angle="{Binding XAxisLabelRotation, 
           RelativeSource={RelativeSource 
             AncestorType={x:Type ContentControl}}, 
           UpdateSourceTrigger=PropertyChanged, 
           Converter={StaticResource AngleConverter}}" ..> 

,並奇蹟般地工作!

WPF不可預知的世界?

+0

我所要做的就是將ElementName = ...添加到我要綁定到的數據上下文根元素的名稱上(在我的例子中,是我的元素駐留的UserControl)。我猜DataContext對於元素內的RotateTransform是不同的:\無論哪種方式,在我的情況下,不需要虛擬轉換器和UpdateSourceTrigger。 –

2

DataContext是否正確?如果此旋轉屬於Content的一部分,則您必須先更改DataContext或將其添加到旋轉的綁定路徑,即將其添加到{Binding Content.XAxisLabelRotation}

你知道如何調試綁定嗎?由於您沒有出現任何綁定錯誤,我會假設您沒有,所以如果出現這種情況,請閱讀this article,並確保您在以後無法自行調試綁定時提供錯誤。

2

你需要這樣的角度綁定:

<RotateTransform Angle="{Binding Path=FontSize, RelativeSource={RelativeSource TemplatedParent}}"/> 

Source