mih*_*jlv 4 wpf attached-properties
我对WPF附加属性有点困惑.当您使用附加属性时,附加属性只能由定义它的类读取和使用?例如,如果我想在按钮上使用一些附加属性作为悬停颜色,我可以从按钮的模板中获取附加属性值,并且我是否可以从按钮访问附加属性来设置胡佛颜色?
Fre*_*lad 13
使用示例添加HB的答案:
例如,如果我想在按钮上使用一些附加属性作为悬停颜色,我可以从按钮的模板中获取附加属性值,并且我是否可以从按钮访问附加属性来设置悬停颜色?
是的,你确定可以.假设您有一个HoverBrush名为SomeClass的类中定义的附加属性,您可以在实例上设置值并在模板中绑定它
<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>
Run Code Online (Sandbox Code Playgroud)
所讨论的附属物是这样定义的
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);
}
}
Run Code Online (Sandbox Code Playgroud)
H.B*_*.B. 10
你看过概述了吗?如果没有,那就去做吧.
附加属性(如依赖项属性)只是注册可以在控件的属性字典中使用的另一个键.您可以在任何地方设置值,您可以在任何地方检索它们,它们不受类型的限制.这意味着您可能只希望在按钮上设置它,但也可以在TextBoxes上设置它.
每个控件都有自己的属性键和值字典,附加属性允许您使用新键将值写入这些字典.由于这些字典是独立的,因此它们可以为通过静态字段属性声明设置和访问的同一属性具有单独的值.
当附加这些属性时,您必须通过GetValue(因为类本身不能提供CLR包装器)来获取值.
| 归档时间: |
|
| 查看次数: |
10613 次 |
| 最近记录: |