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}"/>
相关推荐
执笔论英雄9 小时前
【大模型推理】VLLM 引擎使用
wpf·vllm
LateFrames9 小时前
动画性能比对:WPF / WinUI3 / WebView2
wpf·webview·用户体验·winui3
阿湯哥1 天前
多智能体架构深度解析:企业落地如何选择Skills与SubAgents?
架构·wpf
源之缘-OFD先行者1 天前
自研 WPF 鸟情图表:性能与灵活的双重突破
wpf
Moqiqiuzi1 天前
WPF单实例启动
wpf
Moqiqiuzi1 天前
WPF程序打包成安装包的方法
wpf
码农水水2 天前
国家电网Java面试被问:TCP的BBR拥塞控制算法原理
java·开发语言·网络·分布式·面试·wpf
码农水水2 天前
京东Java面试被问:HTTP/2的多路复用和头部压缩实现
java·开发语言·分布式·http·面试·php·wpf
闻缺陷则喜何志丹2 天前
【C# WPF】TextBox的数据绑定
ui·c#·wpf·mvvm·数据绑定·textbox
码农水水3 天前
得物Java面试被问:大规模数据的分布式排序和聚合
java·开发语言·spring boot·分布式·面试·php·wpf