wpf-动态设置组件【按钮为例】样式

文章速览

坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~

解决方案

创建一个Converter,返回对应的style实现对应的修改

创建多个样式

将创建的样式与Converter的属性绑定

利用Binding 将vm中的属性作为Converter的传参实现动态样式功能

具体实现

Converter 部分

创建一个Converter根据传参,返回相应的样式

csharp 复制代码
    public class ConditionToStyleConverter : IValueConverter
    {
        public Style CurrentStyle { get; set; }
        public Style OptionalStyle { get; set; }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool)value ? CurrentStyle : OptionalStyle ;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new InvalidOperationException();
        }
    }
}

创建样式

xml 复制代码
<Grid.Resources>
	<Style x:Key = "FirstStyle" TargetType="{x:Type Button}" BasedOn = "{StaticResource OptionalStyle}"/>
		<Style x:Key = "FirstStyle" TargetType="{x:Type Button}" BasedOn = "{StaticResource CurrentStyle}"/>
		<local:ConditionToStyleConverter
		 	x:Key = "ConditionToStyleConverter"
		 	CurrentStyle = "{StaticResource CurrentStyle}"
		 	OptionalStyle = "{StaticResource OptionalStyle}"/>
</Grid.Resources>

Binding样式

xml 复制代码
<Button Style="{Binding IsSucceed}",Converter = {StaticResource ConditionToStyleConverter}"/>
相关推荐
hqwest9 分钟前
C#WPF实战出真汁07--【系统设置】--菜品类型设置
开发语言·c#·wpf·grid设计·stackpanel布局
hqwest11 小时前
C#WPF实战出真汁08--【消费开单】--餐桌面板展示
c#·wpf·ui设计·wpf界面设计
orangapple11 小时前
WPF 打印报告图片大小的自适应(含完整示例与详解)
c#·wpf
三千道应用题1 天前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
✎ ﹏梦醒͜ღ҉繁华落℘2 天前
开发WPF项目时遇到的问题总结
wpf
hqwest3 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars3 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest3 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest3 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0074 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度