2008-11-13 41 views
1

我正在Silverlight 2中創建標籤雲,並試圖將數據從List集合綁定到TextBlock上的縮放轉換。當運行這個我得到一個AG_E_PARSER_BAD_PROPERTY_VALUE錯誤。是否有可能將數據綁定值轉換爲Silverlight 2?如果沒有,我可以用FontSize = {Binding Weight * 18}的效果來將標籤的重量乘以基本字體大小?我知道這是行不通的,但計算DataTemplate中的項目屬性值的最佳方法是什麼?silverlight 2綁定數據進行轉換?

<DataTemplate> 
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch" TextWrapping="Wrap" d:IsStaticText="False" Text="{Binding Path=Text}" Foreground="#FF1151A8" FontSize="18" UseLayoutRounding="False" Margin="4,4,4,4" RenderTransformOrigin="0.5,0.5"> 
<TextBlock.RenderTransform> 
    <TransformGroup> 
     <ScaleTransform ScaleX="{Binding Path=WeightPlusOne}" ScaleY="{Binding Path=WeightPlusOne}"/> 
    </TransformGroup> 
</TextBlock.RenderTransform> 

+0

這是我期待在Silverlight 3中的一件事。 – 2009-04-29 14:55:16

回答

0

這個問題似乎是Rule #1 from this post

數據綁定必須是FrameworkElement的的目標。

因此,由於ScaleTransform不是FrameworkElement,因此它不支持綁定。我試圖綁定到一個SolidColorBrush來測試這個,並得到了與ScaleTransform相同的錯誤。

因此,爲了解決這個問題,你可以創建一個控件,公開你的標籤數據類型的依賴屬性。然後有一個屬性更改事件,它將您的標記數據的屬性綁定到控件中的屬性(其中一個屬於比例變換)。這是我用來測試的代碼。

項目控制:

<ItemsControl x:Name="items"> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <local:TagControl TagData="{Binding}" /> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

標籤控制XAML:

<UserControl x:Class="SilverlightTesting.TagControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    > 
    <TextBlock x:Name="text" TextWrapping="Wrap" FontSize="18" Margin="4,4,4,4"> 
     <TextBlock.RenderTransform> 
      <ScaleTransform x:Name="scaleTx" /> 
     </TextBlock.RenderTransform> 
    </TextBlock> 
</UserControl> 

標籤控制代碼:

public partial class TagControl : UserControl 
{ 
    public TagControl() 
    { 
     InitializeComponent(); 
    } 

    public Tag TagData 
    { 
     get { return (Tag)GetValue(TagDataProperty); } 
     set { SetValue(TagDataProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for TagData. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty TagDataProperty = 
     DependencyProperty.Register("TagData", typeof(Tag), typeof(TagControl), new PropertyMetadata(new PropertyChangedCallback(TagControl.OnTagDataPropertyChanged))); 

    public static void OnTagDataPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) 
    { 
     var tc = obj as TagControl; 
     if (tc != null) tc.UpdateTagData(); 
    } 

    public void UpdateTagData() 
    { 
     text.Text = TagData.Title; 
     scaleTx.ScaleX = scaleTx.ScaleY = TagData.Weight; 
     this.InvalidateMeasure(); 
    } 

} 

好像矯枉過正只設置一個單一的屬性,但我不能」找一個更簡單的方法。