现在有类似需求:根据textbox字符串是否为空,设置按钮是否可见
首先定义转换类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace ValueConverters
{
public class ValueConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool isenable = true;
if (string.IsNullOrEmpty(value.ToString()))
{
isenable = false;
}
return isenable;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
根据textbox值设置CheckBox是否选中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace ValueConverters
{
class CheckBoxCheckConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.ToString().ToUpper() == "MARRIED")
{
return true;
}
else
{
return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool married = System.Convert.ToBoolean(value);
if (married == true)
return "Married";
else
return "Unmarried";
}
}
}
main窗体 xaml文件设置
<Window x:Class="ValueConverters.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ValueConverters"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:ValueConverter x:Key="valueconverter"></local:ValueConverter>
<local:CheckBoxCheckConverter x:Key="checkBoxCheckConverter"></local:CheckBoxCheckConverter>
</Window.Resources>
<Grid>
<TextBlock Text="Value Converter Exampkle" HorizontalAlignment="Stretch" VerticalAlignment="Top" TextAlignment="Center"></TextBlock>
<TextBox Name="txtFirstName" HorizontalAlignment="Left" VerticalAlignment="Top" Height="36" Width="255" Margin="136,38,0,0" ></TextBox>
<Button Content="Click" HorizontalAlignment="Left" VerticalAlignment="Top" Height="23" Width="50" Margin="230,101,0,0" IsEnabled="{Binding Path=Text, ElementName=txtFirstName,Converter={StaticResource valueconverter}}"></Button>
<CheckBox Content="Married" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="307,108,0,0" IsChecked="{Binding Path=Text, ElementName=txtFirstName,Converter={StaticResource checkBoxCheckConverter}}"></CheckBox>
<TextBlock Text="MultiValue Converter Exampkle" HorizontalAlignment="Stretch" VerticalAlignment="Top" TextAlignment="Center" Margin="10,146,-10,0"></TextBlock>
</Grid>
</Window>