geo*_*ski 3 wpf enums binding textbox
我将textbox.text值绑定到枚举类型.我的枚举看起来像那样
public enum Type
{
Active,
Selected,
ActiveAndSelected
}
Run Code Online (Sandbox Code Playgroud)
我要做的就是在文本框"Active Mode"而不是"Active"上显示,依此类推.有可能吗?如果我能在XAML中完成它会很棒 - 因为我在样式文件style.xaml中有所有绑定
我试图使用描述属性,但似乎这还不够
恕我直言,使用转换器是一种更好的方法.
您应该做的第一件事是实现一个简单的属性,以便为您的枚举元素添加一些元数据.这是一个基本的例子(为简单起见没有国际化):
public enum StepStatus {
[StringValue("Not done yet")]
NotDone,
[StringValue("In progress")]
InProgress,
[StringValue("Failed")]
Failed,
[StringValue("Succeeded")]
Succeeded
}
Run Code Online (Sandbox Code Playgroud)
接下来,您可以编写一个实用程序类,它可以使用反射从枚举元素转换为相应的StringValue表示.在谷歌"字符串枚举在C#中 - CodeProject上"搜索,你会发现在CodeProject的这篇文章(对不起,我的低信誉不会让我添加链接.)
现在,您可以实现一个转换器,只需将转换委托给实用程序类:
[ValueConversion(typeof(StepStatus), typeof(String))]
public class StepStatusToStringConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture){
String retVal = String.Empty;
if (value != null && value is StepStatus) {
retVal = StringEnum.GetStringValue((StepStatus)value);
}
return retVal;
}
/// <summary>
/// ConvertBack value from binding back to source object. This isn't supported.
/// </summary>
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture) {
throw new Exception("Can't convert back");
}
}
Run Code Online (Sandbox Code Playgroud)
最后,您可以在XAML代码中使用转换器:
<resourceWizardConverters:StepStatusToStringConverter x:Key="stepStatusToStringConverter" />
...
<TextBox Text="{Binding Path=ResourceCreationRequest.ResourceCreationResults.ResourceCreation, Converter={StaticResource stepStatusToStringConverter}}" ... />
Run Code Online (Sandbox Code Playgroud)
检查以下页面 ; 它举了一个支持国际化的例子,但基本上原理是一样的..
对于这种简单的情况,您不需要转换器.请使用Stringformat.前导'{}'是一个转义序列,用于告诉解析器您不打算将它们用于另一个嵌套标记.如果在绑定文本之前添加文本(由"{0}"表示),则可以删除它们.
<Window x:Class="TextBoxBoundToEnumSpike.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBox Text="{Binding ModeEnum,StringFormat={}{0} Mode}"/>
<Button Click="Button_Click" Height=" 50">
Change to 'Selected'
</Button>
</StackPanel>
</Window>
using System.ComponentModel;
using System.Windows;
namespace TextBoxBoundToEnumSpike
{
public partial class MainWindow : Window,INotifyPropertyChanged
{
private ModeEnum m_modeEnum;
public MainWindow()
{
InitializeComponent();
DataContext = this;
ModeEnum = ModeEnum.ActiveAndSelected;
}
public ModeEnum ModeEnum
{
set
{
m_modeEnum = value;
if (PropertyChanged!=null)PropertyChanged(this,new PropertyChangedEventArgs("ModeEnum"));
}
get { return m_modeEnum; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void Button_Click(object sender, RoutedEventArgs e)
{
ModeEnum = ModeEnum.Selected;
}
}
public enum ModeEnum
{
Active,
Selected,
ActiveAndSelected
}
}
Run Code Online (Sandbox Code Playgroud)