Setter,但不用于WPF中的Style



我知道触发器和setter在WPF中是如何工作的,我知道setter只能改变Style属性。对于非样式属性是否有类似Setter的东西?我真的希望能够更改在XAML中实例化的自定义对象的属性。什么好主意吗?

Edit:虽然setter可以更新任何依赖属性,但我试图在EventTrigger中做到这一点,我忘了指定。有这种变通方法,但我不确定它是否真的是最佳实践。它使用故事板和ObjectAnimationUsingKeyFrames。这有什么问题吗?

使用Blend SDK中的Interactivity,你可以在XAML中做到这一点,你只需要创建一个TriggerAction来设置属性。


Edit:在另一个命名空间中已经有这样的操作: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>

您是否声明了要设置为依赖属性的属性?我找不到我这样做的项目,但我很确定这就是为我解决的问题。

我试着实现一些非常简单的东西,得到以下结果:属性"Type"不是一个DependancyProperty。若要在标记中使用,必须使用可访问的实例属性"type"在目标类型上公开非附加属性。对于附加的属性,声明类型必须提供静态的"GetType"one_answers"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设计器属性网格显示。

最新更新