2011-04-27 32 views
0

我知道如何使用Setter觸發器在WPF中工作,並且我知道Setters只能更改樣式屬性。對於非Style屬性,是否有與Setter等價的東西?我真的希望能夠改變在XAML中實例化的自定義對象的屬性。有任何想法嗎?安裝程序,但不適用於WPF中的樣式?

編輯:雖然Setters可以更新任何依賴項屬性,但我試圖在EventTrigger中執行此操作,而我忘記了指定。有this解決方法,但我不確定是否真的是最佳實踐。它使用故事板和ObjectAnimationUsingKeyFrames。這有什麼不對嗎?

+1

二傳手實際上並不是只有樣式屬性。他們可以更改任何'DependencyProperty',無論是否使用風格。 – 2011-04-27 18:24:44

+0

@Fyodor Soikin:該提問者可能意味着DependencyProperties,並希望設置一個正常的CLR屬性。 – 2011-04-27 18:31:57

+0

這沒什麼不對,但是它對你自己的對象有用嗎?它的屬性是可動態的還是DependencyProperties? – 2011-04-27 18:33:53

回答

1

Blend SDK使用Interactivity您可以在XAML中執行此操作,您只需創建一個設置該屬性的TriggerAction


編輯:中已經有另一個命名空間這樣的動作:ChangePropertyAction

在XAML中,你可以使用此命名空間:http://schemas.microsoft.com/expression/2010/interactions


測試的例子:

public class PropertySetterAction : TriggerAction<Button> 
{ 
    public object Target { get; set; } 
    public string Property { get; set; } 
    public object Value { get; set; } 

    protected override void Invoke(object parameter) 
    { 
     Type type = Target.GetType(); 
     var propertyInfo = type.GetProperty(Property); 
     propertyInfo.SetValue(Target, Value, null); 
    } 
} 
<StackPanel> 
    <StackPanel.Resources> 
     <obj:Employee x:Key="myEmp" Name="Steve" Occupation="Programmer"/> 
    </StackPanel.Resources> 
    <TextBlock> 
     <Run Text="{Binding Source={StaticResource myEmp}, Path=Name}"/> 
     <Run Name="RunChan" Text=" - "/> 
     <Run Text="{Binding Source={StaticResource myEmp}, Path=Occupation}"/> 
    </TextBlock> 
    <Button Content="Demote"> 
     <i:Interaction.Triggers> 
      <i:EventTrigger EventName="Click"> 
       <t:PropertySetterAction Target="{StaticResource myEmp}" 
             Property="Occupation" 
             Value="Coffee Getter"/> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
    </Button> 
</StackPanel> 

請注意,使用Value作爲對象時,如果輸入值作爲屬性(Value="Something"),則不會發生ValueConversion,它將被解釋爲字符串。要設置int例如,你可以這樣做:

xmlns:sys="clr-namespace:System;assembly=mscorlib" 
<t:PropertySetterAction Target="{StaticResource myEmp}" 
         Property="Id"> 
    <t:PropertySetterAction.Value> 
     <sys:Int32>42</sys:Int32> 
    </t:PropertySetterAction.Value> 
</t:PropertySetterAction> 
0

您是否聲明瞭要設置爲依賴屬性的屬性?我找不到這個項目,但我確定這是爲我修復的。

我試着實現一些非常簡單的事情,並得到以下內容: 屬性「類型」不是一個DependancyProperty。要在標記中使用,必須在目標類型上暴露非附加屬性,並使用可訪問的實例屬性「類型」。對於附加屬性,聲明類型必須提供靜態「GetType」和「SetType」方法。

下面是從礦的另一項目中的屬性扶養登記例如:

Public Shared TitleProperty As DependencyProperty = DependencyProperty.Register("Title", GetType(String), GetType(SnazzyShippingNavigationButton)) 

在上述例子中,SnazzyShippingNavigationButton是類名,其中該屬性是一個構件。

和相關財產申報:

<Description("Title to display"), _ 
Category("Custom")> _ 
Public Property Title() As String 
    Get 
     Return CType(GetValue(TitleProperty), String) 
    End Get 
    Set(ByVal value As String) 
     SetValue(TitleProperty, value) 
    End Set 
End Property 

描述和類別屬性才真正適用於IDE設計器屬性網格顯示。

相關問題