wpf 数据绑定 数据转换

1.概要

数据绑定,有时候绑定的数据源和目标的数据类型不同,这时候就需要转换。

2.代码

2.1 xaml(eXtensible Application Markup Language) 可扩展应用程序标记语言

复制代码
<Window x:Class="WpfApp6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp6"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="300">
    <Window.Resources>
        <local:boolchange x:Key="boolkey"></local:boolchange>
    </Window.Resources>
    <StackPanel>
        <TextBox Name="source1"></TextBox>
        <TextBlock Text="YES"></TextBlock><CheckBox IsChecked="{Binding ElementName=source1, Path=Text,Converter={StaticResource boolkey}}"></CheckBox>
    </StackPanel>
</Window>

2.2 code

复制代码
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp6
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    public class boolchange : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string? str = value.ToString().ToLower();
            switch(str)
            {
                case "yes":
                    return true;
                case "no": 
                    return false;    
            }
            return false;
        }

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

3.运行结果

相关推荐
Ulyanov5 小时前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
ai_coder_ai5 小时前
自动化脚本ui编程之垂直滚动布局(vscroll)
ui·autojs·自动化脚本·冰狐智能辅助·easyclick
久爱物联网8 小时前
【WinForm UI控件系列】BarPlot柱状图控件
ui·ui控件·winformui·csharpui控件·桌面ui控件
for_ever_love__9 小时前
UI学习:多界面传值的正向传值(属性传值)和反向传值(代理传值)
学习·ui·ios·objective-c
c#上位机11 小时前
wpf路由事件
wpf
Python私教11 小时前
FuturesDesk:配置驱动 UI 的 Electron 金融桌面应用模板
ui·金融·electron
椰羊~王小美11 小时前
LVGL 界面UI库
ui
久爱物联网15 小时前
【WinForm UI控件系列】Breadcrumb 面包屑控件,支持三种样式
ui·breadcrumb·面包屑控件·winformui·csharpui控件·桌面ui控件
久爱物联网15 小时前
【WinForm UI控件系列】PieChart饼状图控件
ui·winformui控件·c#控件ui·桌面应用ui控件·gdi绘制控件
nashane15 小时前
HarmonyOS 鸿蒙 2026 全栈实战:从手势驱动到分布式数据落地的完整架构
wpf·harmony app