我知道使用Setters的触发器如何在WPF中工作,而且我知道Setters只能更改样式属性。对于非样式属性,是否存在与Setter等效的内容?我非常希望能够更改在XAML中实例化的自定义对象上的属性。有什么想法吗?
编辑:虽然设置器可以更新任何依赖项属性,但我尝试在EventTrigger中进行此操作,而我忘记了指定该属性。有这的解决办法,但我不确定它是否真的是最佳实践。它使用故事板和ObjectAnimationUsingKeyFrames。这个有什么问题吗?
发布于 2011-04-27 18:47:45
使用XAML中的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是一个对象,默认情况下不会发生ValueConversion,如果您输入一个属性值(Value="Something"),它将被解释为一个字符串。例如,要设置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>发布于 2011-04-27 18:36:35
是否声明了要设置为依赖项属性的属性?我找不到我做这件事的项目,但我很确定这就是我要做的事。
我尝试实现一些非常简单的东西,得到如下结果:属性"Type“不是DependancyProperty。要在标记中使用,必须在目标类型和可访问实例属性" type“上公开非附加属性。对于附加属性,声明类型必须提供静态"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 designer属性网格显示。
https://stackoverflow.com/questions/5808697
复制相似问题