WPF——自定义RadioButton

2024-09-03 07:36
文章标签 自定义 wpf radiobutton

本文主要是介绍WPF——自定义RadioButton,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求

需要做一组单选按钮,只要单选按钮的显示内容与需要匹配的内容一样,则该单选按钮就为选中状态,否则则为不选中状态;且需要将当前选中状态保存,后续再进入此页面时,匹配内容为此次的保存状态。

如下所示,3个单选按钮分别为Test1、Test2、Test3,需要匹配的内容为Test2。那么Test2就为选中状态,其它两个就为非选中状态。

深入分析

通过对需求的了解,可得出下述进一步需求:

单选按钮需要在选中状态下,需要将当前选中内容保存下来,也就是说需要将当前的选中内容作为匹配更新到VM中,在VM中再去实现相应的状态保存。

单选按钮在非选中状态下,可不将当前单选按钮的匹配内容清除(也可以清除),同时要保证这一组单选按钮有一个按钮是选中状态。

根据上述分析,从代码实现上需要考虑以下问题:

匹配内容需要绑定。

首次加载控件时,需要根据匹配内容设置当前控件是否为选中状态。

选中时需要将匹配内容更新,以便VM根据匹配内容的变化以保存它。

取消选中时,可考虑清空匹配内容,若要清空匹配匹配内容,那么在保存匹配内容时需要注意,不要将空值作为匹配内容的一个值保存;或者说空值不需要触发匹配内容的保存功能。

代码实现

按上述深入分析,那么仅需要自定义一个自定义单选按钮即可实现相应功能。详细代码如下:

    public class CustomRadio : RadioButton{static CustomRadio(){}public string Text{get { return (string)GetValue(TextProperty); }set { SetValue(TextProperty, value); }}public static readonly DependencyProperty TextProperty =DependencyProperty.Register("Text", typeof(string), typeof(CustomRadio), new PropertyMetadata(string.Empty, TextChanged));private static void TextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){var radio = (CustomRadio)d;var ntxt = e.NewValue as string;// 获取Content属性的BindingExpression//var bindingExpression = BindingOperations.GetBindingExpression(radio, ContentControl.ContentProperty);//if (bindingExpression != null)//{//    // 强制更新绑定//    bindingExpression.UpdateTarget();//}// 现在可以获取到更新后的Content值var content = radio.Content?.ToString();if (content == ntxt){radio.IsChecked = true;}else{radio.IsChecked = false;}}protected override void OnChecked(RoutedEventArgs e){base.OnChecked(e);// 当RadioButton被选中时,更新Text属性Text = Content == null ? string.Empty : Content.ToString();}protected override void OnUnchecked(RoutedEventArgs e){base.OnUnchecked(e);// 当RadioButton未被选中时,清空Text属性Text = string.Empty;}}

注:上述代码中的Text依赖属性即是用于匹配内容的绑定。

以上为测试时使用的VM:

    internal partial class MainWindowViewModel : ObservableObject{[ObservableProperty]TestMethod testMethod = new TestMethod();[ObservableProperty]string testName = "Test2";[ObservableProperty]ObservableCollection<Student> students = [new(){Id=1,Name="test1",Age=12,Grade=1,Y=50},new(){Id=2,Name="test2",Age=12,Grade=2,Y=100},new(){Id=3,Name="test3",Age=12,Grade=3,Y=150},new(){Id=4,Name="test4",Age=12,Grade=4,Y=200},new(){Id=5,Name="test5",Age=12,Grade=5,Y=250},];Timer timer = new();public MainWindowViewModel(){timer.Start();timer.Interval = 2000;timer.Elapsed += Timer_Elapsed;}[RelayCommand]public void StopTimer(){timer.Stop();}private void Timer_Elapsed(object? sender, ElapsedEventArgs e){Random random = new();var index = random.Next(0, Students.Count);Students[index].Grade = random.Next(1, 101);var order = Students.OrderBy(e => e.Grade);//Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>//{}));int i = 0;foreach (Student student in order){student.Id = ++i;student.OldY = student.Y;student.Y = i * 50;student.IsUp = student.Y > student.OldY;//Students[i - 1] = student;}}}public partial class Student : ObservableObject{[ObservableProperty]private int id;[ObservableProperty]private string name = string.Empty;[ObservableProperty]private int age;[ObservableProperty]private int grade;[ObservableProperty]private int y;[ObservableProperty]private int oldY;[ObservableProperty]private bool isUp;}public partial class TestMethod : ObservableObject{[ObservableProperty]string one = "Test1";[ObservableProperty]string two = "Test2";[ObservableProperty]string three = "Test3";}

以下为测试时使用的WPF UI:

<Windowx:Class="WpfApp1.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:control="clr-namespace:WpfApp1.Control"xmlns:converter="clr-namespace:WpfApp1.Converter"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:local="clr-namespace:WpfApp1"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:viewmodels="clr-namespace:WpfApp1.VM"x:Uid="Window1Title"Width="800"Height="450"mc:Ignorable="d"><Window.DataContext><viewmodels:MainWindowViewModel /></Window.DataContext><Window.Resources></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="100" /><RowDefinition Height="*" /></Grid.RowDefinitions><StackPanel><control:CustomRadioContent="{Binding TestMethod.One}"GroupName="test1"Text="{Binding TestName, Mode=TwoWay}" /><control:CustomRadioContent="{Binding TestMethod.Two}"GroupName="test1"Text="{Binding TestName, Mode=TwoWay}" /><control:CustomRadioContent="{Binding TestMethod.Three}"GroupName="test1"Text="{Binding TestName, Mode=TwoWay}" /><Button Command="{Binding StopTimerCommand}" Content="Close" /></StackPanel></Grid>
</Window>

更优实现

然在搞定此自定义的RadioButton后,若只是单一的一行RadioButton,那么其实还可以有其它实现方式,比如用集合控件。

比如使用ListBox,这样还不用多次使用自定义的RadioButton,只需要绑定时将VM中的集合绑定于ListBox即可。

以下为ListBox结合CustomRadio的实现:

        <StackPanel><ListBox x:Name="list" ItemsSource="{Binding Methods}"><ListBox.ItemsPanel><ItemsPanelTemplate><StackPanel Orientation="Horizontal" /></ItemsPanelTemplate></ListBox.ItemsPanel><ListBox.ItemTemplate><DataTemplate><control:CustomRadioMargin="5"Content="{Binding}"GroupName="test1"Text="{Binding DataContext.TestName, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" /></DataTemplate></ListBox.ItemTemplate></ListBox><Button Command="{Binding StopTimerCommand}" Content="{x:Static loc:Resources.TextBlock1_TextBlock_Text}" /></StackPanel>

然,上述ListBox的实现并不是最好的,它存在以下问题:

每次ListBox内的单选按钮的选中与取消,会触发CustomRadio中的方法OnChecked(原按钮)与OnUnchecked(现按钮),这有两次调用才能将匹配内容更新;而只要改为ListBox的选中事件,那么只需要调用一次就可以更新匹配内容,也就是说从性能上来说,使用ListBox与CustomRadio的组合不是最优,最好是完全自定义ListBox来实现需求。

这篇关于WPF——自定义RadioButton的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1132421

相关文章

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

Linux中的自定义协议+序列反序列化用法

《Linux中的自定义协议+序列反序列化用法》文章探讨网络程序在应用层的实现,涉及TCP协议的数据传输机制、结构化数据的序列化与反序列化方法,以及通过JSON和自定义协议构建网络计算器的思路,强调分层... 目录一,再次理解协议二,序列化和反序列化三,实现网络计算器3.1 日志文件3.2Socket.hpp

C语言自定义类型之联合和枚举解读

《C语言自定义类型之联合和枚举解读》联合体共享内存,大小由最大成员决定,遵循对齐规则;枚举类型列举可能值,提升可读性和类型安全性,两者在C语言中用于优化内存和程序效率... 目录一、联合体1.1 联合体类型的声明1.2 联合体的特点1.2.1 特点11.2.2 特点21.2.3 特点31.3 联合体的大小1

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

一文详解Java Stream的sorted自定义排序

《一文详解JavaStream的sorted自定义排序》Javastream中的sorted方法是用于对流中的元素进行排序的方法,它可以接受一个comparator参数,用于指定排序规则,sorte... 目录一、sorted 操作的基础原理二、自定义排序的实现方式1. Comparator 接口的 Lam