对WPF使用依赖属性修改元素样式属性

认知尚浅,如有错误,愿闻其详!

  起初,对依赖属性是一点都不了解的,完全不明白其用意何在,他的出发点在哪。看了很多文章,也没看明白。不是作者没写好,而是我比较浮躁!最后是在一个视频中,看到了使用依赖属性,才开始明白其用法之一,修改控件表现属性。
  其实,其并不是很难以理解,我们可以理解成他是类似属性的东西,同样的有着声明,get,set方法。
详细的技术网络上很多,大家可以去深入了解。我这里主要是形象的说明他在修改一些属性的问题上的使用。

需求

  我在便签项目开发中,有个需求就是对便签的窗体的位置、颜色、透明度,对文本的字体、大小等进行设置。以往的Winform中,如果要实现以上功能,需要获取窗口对象,然后获取相应的属性,进行属性值的修改。如下代码:

  //设置窗口属性
 this.BackColor = Color.Blue;
 this.Location = new Point(100,100);
  //文本属性设置
 this.textBox.Font = new Font( new FontFamily("微软雅黑") , 12f, FontStyle.Bold);

  同样的方式,来到WPF,是行不通的,但是,我们可以通过另一种更灵活的方式去实现上述的功能,也就是依赖属性的使用。在我看来,WPF的界面设计模式更倾向于HTML形式去设计界面,使得界面更具多样化。所以依赖属性的使用也有点类似于ASP.NET中对静态页面的数据填充。如下是一个例子:

实现

首先,对依赖属性进行声明,为DependencyProperty类型属性

//依赖属性声明
 public static DependencyProperty viewBackgroundProperty;//窗口背景颜色

其次是对属性的封装,无非就是get,set

//依赖属性封装
public string viewBackground
{
     get { return (string)GetValue(viewBackgroundProperty); }
     set { SetValue(viewBackgroundProperty , value); }
}

然后是依赖属性的注册,此步骤可以与声明一起进行,该阶段主要是注册依赖属性的属性名称、属性类型、所属类型、最后是属性的默认值,元数据

//依赖属性注册,可直接声明时注册赋值
 viewBackgroundProperty = DependencyProperty.Register("viewBackground" , typeof(string) , typeof(StickyNoteView) ,new FrameworkPropertyMetadata("#FFAEB9"));

最后,是于XAML下绑定依赖属性 ,分别可以看到Opacity与Color属性的对应值都绑定着依赖属性格式为{Binding ElementName=stickyNoteViewProp, Path=backgroundOpacity} Binding是关键字,ElementName 绑定元素名 backgroundOpacity绑定的属性名

<!--绑定依赖属性-->
  <Window.Background  Name="stickyNoteViewProp">
        <SolidColorBrush Opacity="{Binding ElementName=stickyNoteViewProp, Path=backgroundOpacity}" Color="{Binding ElementName=stickyNoteViewProp, Path=viewBackground}"></SolidColorBrush>
    </Window.Background>

这样,我们在就可以在主程序上赋值依赖属性值,实现相应的修改。以我的便签项目为例,如下

   /// <summary>
        /// 重新载入主题
        /// </summary>
        public void ReloadTheme()
        {
            Theme th = Window.Themes[_theme];
            if (th.Name == "用户") th = CustomTheme;
           

            this.viewBackground =th.BackColor;
            this.contentFontColor= th.TextColor;
            this.navBarBackground = th.TopBarColor;
        }

效果

最后的便签效果:

11467412-9cdae9b23d9c13ed.gif
依赖属性.gif

猜你喜欢

转载自blog.csdn.net/weixin_34208185/article/details/90859630