代码
MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingTest" x:Class="BindingTest.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:TextToBooleanConverter x:Key="TextToBooleanConverter"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Label x:Name="lblValue" Content="0" FontSize="100" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<CheckBox IsChecked="{Binding Content, Converter={StaticResource TextToBooleanConverter}, ElementName=lblValue, Mode=TwoWay}" Grid.Column="1" x:Name="chkValue" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5">
<CheckBox.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="10" ScaleY="10"/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</CheckBox.RenderTransform>
</CheckBox>
<Button x:Name="btnSet0" Grid.Row="1" Grid.Column="0" Content="0" FontSize="100" Click="btnSet0_Click"/>
<Button x:Name="btnSet1" Grid.Row="1" Grid.Column="1" Content="1" FontSize="100" Click="btnSet1_Click"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 BindingTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnSet0_Click(object sender, RoutedEventArgs e)
{
lblValue.Content = "0";
}
private void btnSet1_Click(object sender, RoutedEventArgs e)
{
lblValue.Content = "1";
}
}
}
TextToBooleanConverter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Globalization;
namespace BindingTest
{
public class TextToBooleanConverter : IValueConverter
{
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
{
if (value.ToString() == "1")
{
return true;
}
else
{
return false;
}
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
{
bool b = (bool)value;
if (b == true)
{
return "1";
}
else
{
return "0";
}
}
}
}
运行结果
label的Content属性(绑定源)与checkbox控件的isChecked属性(绑定目标)绑定,绑定方向为双向,两者属性通过TextToBooleanConverter实现数据类型的转换。
VS 2013(.Net 4.5) 编译通过。