Converter在WPF/XAML中扮演着非常重要的角色,特别是在数据绑定和值转换方面。下面我将详细介绍如何在XAML和后台代码中使用Converter,特别是布尔型转换的应用。
一、XAML中的值转换器(Value Converter)
1. 创建布尔值转换器
首先需要创建一个实现IValueConverter接口的转换器类:
using System;
using System.Globalization;
using System.Windows.Data;
public class BoolToTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool boolValue)
{
// 可以添加参数处理,如parameter指定true/false时的显示文本
return boolValue ? "是" : "否";
}
return "无效";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string strValue)
{
return strValue == "是";
}
return false;
}
}
2. 在XAML中使用转换器
<Window x:Class="ConverterDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ConverterDemo"
Title="Bool Converter Demo" Height="200" Width="300">
<Window.Resources>
<local:BoolToTextConverter x:Key="BoolToTextConverter"/>
</Window.Resources>
<StackPanel Margin="10">
<CheckBox x:Name="myCheckBox" Content="是否同意条款" IsChecked="True"/>
<TextBlock Margin="0,10,0,0"
Text="{Binding ElementName=myCheckBox, Path=IsChecked,
Converter={StaticResource BoolToTextConverter}}"/>
<Button Content="切换状态" Margin="0,10,0,0"
Click="ToggleButton_Click"/>
</StackPanel>

最低0.47元/天 解锁文章
479

被折叠的 条评论
为什么被折叠?



