從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>
二傳手實際上並不是只有樣式屬性。他們可以更改任何'DependencyProperty',無論是否使用風格。 – 2011-04-27 18:24:44
@Fyodor Soikin:該提問者可能意味着DependencyProperties,並希望設置一個正常的CLR屬性。 – 2011-04-27 18:31:57
這沒什麼不對,但是它對你自己的對象有用嗎?它的屬性是可動態的還是DependencyProperties? – 2011-04-27 18:33:53