我正在尝试将数据绑定到WPF中的文本框。但它失败了。我在同一个应用程序中将Enum绑定到单选按钮,这很好用;但是当我尝试将Enum绑定到文本框时,它会失败。我做错了什么?
<Grid.Resources>
<Style TargetType="{x:Type Button}" x:Key="formatTextStyle">
<Setter Property="FontFamily" Value="Palatino Linotype"></Setter>
<Setter Property="Width" Value="30"></Setter>
<Setter Property="FontSize" Value ="14"></Setter>
<Setter Property="CommandTarget" Value="{Binding ElementName=mainRTB}"></Setter>
</Style>
<Style TargetType="{x:Type MenuItem}" x:Key="formatImageStyle">
<Setter Property="Width" Value="30"></Setter>
<Setter Property="CommandTarget" Value="{Binding ElementName=mainRTB}"></Setter>
</Style>
<local:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
<local:StatusToStringConverter x:Key="StatusToStringConverter" />
</Grid.Resources>
<RadioButton IsEnabled="False" Click="DisplayFormatChanged" Name="BinaryButton" Content="_Binary" IsChecked="{Binding Path=DisplayFormat, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:displayFormat.Binary}}" />
<RadioButton IsEnabled="False" Click="DisplayFormatChanged" Name="HexButton" Content="_Hex" IsChecked="{Binding Path=DisplayFormat, Mode=TwoWay, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:displayFormat.Hex}}" />
<TextBlock Name="Status" IsEnabled="False" Text="{Binding Path=Status, Mode=TwoWay, Converter={StaticResource StatusToStringConverter}, ConverterParameter={x:Static local:Status.NotStarted}}"/>
背后的代码看起来像这样:
namespace Editor
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{ //rest of my code goes in here}
[ValueConversion(typeof(displayFormat), typeof(Boolean))]
public class EnumToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
}
[ValueConversion(typeof(Status), typeof(String))]
public class StatusToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (Status)Enum.Parse(typeof(Status), value.ToString(), true);
}
}
}