110,545
社区成员
发帖
与我相关
我的任务
分享
public class EnumToTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
TestEnum te = (TestEnum)value;
if(te == TestEnum.Test1)
{
return "This is Test1";
}
else if (te == TestEnum.Test2)
{
return "This is Test2";
}
else if (te == TestEnum.Test3)
{
return "This is Test3";
}
else if (te == TestEnum.Test4)
{
return "This is Test4";
}
return "Null";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value == null)
{
return TestEnum.Null;
}
string text = value.ToString();
if(text == "This is Test1")
{
return TestEnum.Test1;
}
else if(text == "This is Test2")
{
return TestEnum.Test2;
}
else if (text == "This is Test3")
{
return TestEnum.Test3;
}
else if (text == "This is Test4")
{
return TestEnum.Test4;
}
else
{
return TestEnum.Null;
}
}
}
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:EnumToTextConverter x:Key="etc"/>
</Window.Resources>
<Grid>
<TextBox Text="{Binding TestEnum,Converter={StaticResource etc}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public enum TestEnum : int
{
Null = 0,
Test1 = 1,
Test2 = 2,
Test3 = 3,
Test4 = 4,
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TestEnum _testEnum = TestEnum.Test1;
public TestEnum TestEnum
{
get => _testEnum;
set
{
_testEnum = value;
PropertyChanged(this, new PropertyChangedEventArgs("TestEnum"));
}
}
}