2008-11-11 19 views
4

我有這樣一個類:我需要做什麼才能使屬性元素語法適用於Silverlight中的自定義附加屬性?

public class Stretcher : Panel { 

    public static readonly DependencyProperty StretchAmountProp = DependencyProperty.RegisterAttached("StretchAmount", typeof(double), typeof(Stretcher), null); 

    public static void SetStretchAmount(DependencyObject obj, double amount) 
    { 
     FrameworkElement elem = obj as FrameworkElement; 
     elem.Width *= amount; 

     obj.SetValue(StretchAmountProp, amount); 
    } 
} 

我可以使用屬性語法在XAML中設置的伸縮量屬性:

<UserControl x:Class="ManagedAttachedProps.Page" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:map="clr-namespace:ManagedAttachedProps" 
    Width="400" Height="300"> 

    <Rectangle Fill="Aqua" Width="100" Height="100" map:Stretch.StretchAmount="100" /> 

</UserControl> 

,我的矩形拉長,但我不能使用屬性像這樣的元素語法:

<UserControl x:Class="ManagedAttachedProps.Page" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:map="clr-namespace:ManagedAttachedProps" 
    Width="400" Height="300"> 

    <Rectangle Fill="Aqua" Width="100" Height="100"> 
     <map:Stretcher.StretchAmount>100</map:Stretcher.StretchAmount> 
    </Rectangle> 
</UserControl> 

與屬性元素語法我的組塊似乎被完全忽略(我甚至可以把無效的雙值),SetStretchAmount方法永遠不會被調用。

我知道可以這樣做,因爲VisualStateManager可以做到這一點。我試過使用除雙以外的類型,但似乎沒有任何工作。

回答

2

我想我明白了這一點,雖然我不完全確定我理解它爲什麼會起作用。

爲了讓你的例子工作,我必須創建一個稱爲Stretch的自定義類型,其中包含一個名爲StretchAmount的屬性。一旦我做到了,把它放在它工作的property元素標籤裏面。否則它不會被調用。

public class Stretch 
{ 
    public double StretchAmount { get; set; } 
} 

和物業改爲..

public static readonly DependencyProperty StretchAmountProp = DependencyProperty.RegisterAttached("StretchAmount", typeof(Stretch), typeof(Stretcher), null); 

public static void SetStretchAmount(DependencyObject obj, Stretch amount) 
{ 
    FrameworkElement elem = obj as FrameworkElement; 
    elem.Width *= amount.StretchAmount; 
    obj.SetValue(StretchAmountProp, amount); 
} 

到您不使用屬性元素,你需要創建一個自定義類型轉換器允許該得到這個方案中的工作上班。

希望這會有所幫助,儘管它沒有解釋我仍然試圖理解的原因。

順便說一句 - 對於一個真正的腦筋急轉彎,請看一下反射器中的VisualStateManager。 VisualStateGroups的依賴屬性和setter都是內部

+0

很有意思,有些奇怪。當我有機會訪問一臺Windows機器時,我會明天再試一次,並確保在其工作時給出答案。謝謝! – Jacksonh 2008-11-12 06:10:49

1

所以科比的解決方案作品,它確實需要一個稍微修改的XAML:

<Rectangle Fill="Aqua" Width="100" Height="100" x:Name="the_rect"> 
     <map:Stretcher.StretchAmount> 
      <map:Stretch StretchAmount="100" /> 
     </map:Stretcher.StretchAmount> 
</Rectangle> 
相關問題