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.运行结果

相关推荐
Wiktok2 小时前
WPF文件命名的核心规则
wpf
TeamDev2 小时前
使用 Docker 部署 DotNetBrowser 应用程序
运维·ui·docker·容器·桌面应用·dotnet·dotnetbrowser
Wiktok2 小时前
WPF.XAML文件属性解析
wpf
Wiktok2 小时前
WPF 中的 <Window> 和 <Application>根级标签讲解
wpf
Nile16 小时前
解密openclaw底层pi-mono架构系列一:5. pi-web-ui
前端·ui·架构
少云清21 小时前
【UI自动化测试】8_TPshop项目实战 _APP-根据频道搜索新闻
ui
Wiktok1 天前
WPF几种布局的讲解
wpf
Bug 挖掘机1 天前
利用OpenClaw+飞书,AI驱动UI自动化测试实战案例来了
软件测试·功能测试·测试开发·ui·飞书
UI设计兰亭妙微1 天前
飞秒激光时域热反射测量系统软件UI界面设计
ui·ui设计公司
少云清1 天前
【UI自动化测试】1_IOS自动化测试 _环境搭建
ui·ios