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

相关推荐
Quz1 小时前
使用Qt Quick Controls创建自定义日历组件
qt·ui·交互
Java林间1 天前
Zookeeper是什么?基于zookeeper实现分布式锁
分布式·zookeeper·wpf
zizisuo1 天前
1.微服务拆分与通信模式
微服务·wpf
just小千1 天前
重学React(一):描述UI
前端·react.js·ui
招风的黑耳2 天前
Axure中继器表格:实现复杂交互设计的利器
ui·表格
程序员秘密基地2 天前
基于c#,wpf,ef框架,sql server数据库,音乐播放器
sql·sqlserver·c#·.net·wpf
Zhen (Evan) Wang2 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
招风的黑耳2 天前
Axure按钮设计分享:打造高效交互体验的六大按钮类型
ui·按钮·动态按钮·按钮设计
Aotman_2 天前
VUE Element-ui Message 消息提示组件自定义封装
前端·javascript·vue.js·ui·elementui·es6