9.附加属性

我们在学习布局控件时,其实也已经使用过附加属性了。下面我们来看一些例子

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button Grid.Row="0" Content="按钮1"/>
    <Button Grid.Row="1" Content="按钮2"/>
</Grid>

上面的代码中,按钮1被放到Grid的第一行中,按钮2被放到Grid的第二行中。通过Grid.Row附加属性完成这一设置。实际上这个Row属性并没有定义在Button中,而是定义在Grid中,且被定义成附加属性

<Canvas>
    <Button Canvas.Left="20" Canvas.Top="20" Content="按钮1"/>
    <Button Canvas.Left="80" Canvas.Top="20" Content="按钮2"/>
</Canvas>
<DockPanel LastChildFill="False">
    <Button DockPanel.Dock="Left" Content="按钮1"/>
    <Button DockPanel.Dock="Right" Content="按钮2"/>
</DockPanel>

综上所述,附加属性定义好后,是附加到别的控件上起作用的。

附加属性的定义

在C#后端代码中,键入propa,然后按下tab键,VS会自动创建一个附加属性的定义模板,如下所示。

public static int GetMyProperty(DependencyObject obj)
{
    return (int)obj.GetValue(MyPropertyProperty);
}
 
public static void SetMyProperty(DependencyObject obj, int value)
{
    obj.SetValue(MyPropertyProperty, value);
}
 
// Using a DependencyProperty as the backing store for MyProperty.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.RegisterAttached(
        "MyProperty", 
        typeof(int), 
        typeof(ownerclass), 
        new PropertyMetadata(0));

附加属性利用DependencyProperty的RegisterAttached方法成员进行注册,在注册的时候要求传入一些参数,与注册依赖属性的参数完全相同。

只不过在设置或读取附加属性时,将采用SetMyProperty和GetMyProperty的形式,并最终利用SetValue和GetValue方法成员完成。哪里来的SetValue和GetValue?原来,在DependencyObject基类中定义了这两个方法成员,它们是WPF属性系统的业务核心。

 

posted @ 2024-01-30 19:12  野码  阅读(77)  评论(0编辑  收藏  举报