# 基础篇

### 依赖属性propdb

```c#
        public int MyProperty
        {
            get { return (int)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));
```

### 附加属性propa

```c#
    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));
```

## xaml资源键类型

<table id="bkmrk-%E5%AE%9A%E4%B9%89%E6%96%B9%E5%BC%8F-%E4%BC%98%E7%82%B9-%E7%BC%BA%E7%82%B9-%E9%80%82%E7%94%A8%E5%9C%BA%E6%99%AF-%E6%99%AE%E9%80%9A%E5%AD%97%E7%AC%A6"><thead><tr><th>定义方式</th><th>优点</th><th>缺点</th><th>适用场景</th></tr></thead><tbody><tr><td>**普通字符串键**</td><td>简单直观，易于使用</td><td>命名冲突风险，无法跨程序集共享</td><td>小型项目，局部资源</td></tr><tr><td>**类型键**</td><td>自动应用，无需显式引用</td><td>灵活性较低</td><td>全局样式，基础样式复用</td></tr><tr><td>**静态资源键**</td><td>强类型支持，可维护性高</td><td>定义稍复杂</td><td>大型项目，组件化开发</td></tr><tr><td>**`ComponentResourceKey`**</td><td>跨程序集支持，语义化标识</td><td>定义和使用复杂</td><td>组件库开发，主题或样式库</td></tr><tr><td>**动态资源键**</td><td>动态绑定，灵活性高</td><td>性能开销</td><td>主题切换，多语言支持</td></tr></tbody></table>

```nginx
//普通字符串键
<Style x:Key="MyButtonStyle" TargetType="Button" />

//类型键（隐式样式）
<Style TargetType="Button">
    <Setter Property="Background" Value="LightBlue" />
</Style>

//静态资源键
public static class ResourceKeys
{
    public static readonly string CloseButtonStyle = "CloseButtonStyle";
}

<Style x:Key="{x:Static local:ResourceKeys.CloseButtonStyle}" TargetType="Button" />

//组件资源键ComponentResourceKey

    public partial class DataTemplateKeys
    {
        public static ComponentResourceKey ItemClose => new ComponentResourceKey(typeof(DataTemplateKeys), "S.DataTemplate.Item.Close");
    }
<DataTemplate x:Key="{ComponentResourceKey ResourceId=S.DataTemplate.Item.Close, TypeInTargetAssembly={x:Type local:DataTemplateKeys}}">

//静态资源键与组件资源键结合

public static class ResourceKeys
{
    public static readonly ComponentResourceKey CloseButtonStyleKey = new ComponentResourceKey(typeof(ResourceKeys), "CloseButtonStyle");
}

<Style x:Key="{x:Static local:ResourceKeys.CloseButtonStyleKey}" TargetType="Button" />

//动态资源键
<Button Style="{DynamicResource MyButtonStyle}" />
```