gpt4 book ai didi

wpf - 附加属性

转载 作者:行者123 更新时间:2023-12-03 18:15:09 24 4
gpt4 key购买 nike

我对 WPF 附加属性有点困惑。当您使用附加属性时,该附加属性只能由定义它的类读取和使用,对吗?例如,如果我想在按钮上使用一些附加属性作为悬停颜色,我可以从按钮的模板中获取附加属性值,并且我可以从按钮访问附加属性以设置悬停颜色吗?

最佳答案

添加到 H.B. 的答案。使用一个例子:

For example if I wanted to use some attached property as a hover color on a button, can I get the attached property value from the button's template, and will I be able access the attached property from the button to set the hover color?



是的,你当然可以。假设您有一个名为 HoverBrush 的附加属性在名为 SomeClass 的类中定义,您可以在实例上设置值并在模板中绑定(bind)到它
<StackPanel>
<StackPanel.Resources>
<ControlTemplate x:Key="MyButtonTemplate" TargetType="{x:Type Button}">
<Border x:Name="border" Background="Gray">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border"
Property="Background"
Value="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=(local:SomeClass.HoverBrush)}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</StackPanel.Resources>
<Button Content="Blue Hover"
local:SomeClass.HoverBrush="Blue"
Template="{StaticResource MyButtonTemplate}"/>
<Button Content="Green Hover"
local:SomeClass.HoverBrush="Green"
Template="{StaticResource MyButtonTemplate}"/>
</StackPanel>

有问题的附加属性定义如下
public class SomeClass
{
public static DependencyProperty HoverBrushProperty =
DependencyProperty.RegisterAttached("HoverBrush",
typeof(Brush),
typeof(SomeClass),
new PropertyMetadata(null));
public static void SetHoverBrush(DependencyObject obj, Brush value)
{
obj.SetValue(HoverBrushProperty, value);
}
public static Brush GetHoverBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(HoverBrushProperty);
}
}

关于wpf - 附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7148946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com