我有一个枚举类型的属性。我将wpf控件的内容绑定到此属性。这将显示枚举值的名称。因此调用枚举的ToString方法。
但是我需要显示值,而不是字符串值。有谁知道怎么做?
这是我的C#代码:
public Camera cam;
private float maxWidth;
Rigidbody2D rigidbody2D;
// Use this for initialization
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
if (cam == null)
{
cam = Camera.main;
}
Vector3 upperCorner = new Vector3(Screen.width, Screen.height, 0.0f);
Vector3 targetWidth = cam.ScreenToWorldPoint(upperCorner);
float SantaBagWidth = GetComponent<Renderer>().bounds.extents.x;
maxWidth = targetWidth.x - SantaBagWidth;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 rawPosition = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 targetPosition = new Vector3(rawPosition.x, 0.0f, 0.0f);
float targetWidth = Mathf.Clamp(targetPosition.x, -maxWidth, maxWidth);
targetPosition = new Vector3(targetWidth, targetPosition.y, targetPosition.z);
rigidbody2D.MovePosition(targetPosition);
}
这是我的XAML:
public enum Animal
{
cat = 0,
dog = 1,
mouse = 2
}
public Animal MyAnimal { get; set; }
void SomeMethod() { MyAnimal = dog; }
答案 0 :(得分:1)
当您绑定到一种类型的值并希望以另一种格式显示它而不是默认的ToString()方法时,您应该使用DataTemplate或IValueConverter。由于XAML是标记语言,因此您无法将枚举值强制转换为标记中的int,因此您应该使用转换器:
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
animals enumValue = (animals)value;
return System.Convert.ToInt32(enumValue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<Window.Resources>
<local:EnumConverter x:Key="conv" />
</Window.Resources>
...
<ContentControl Content="{Binding TheEnumProperty, Converter={StaticResource conv}}" />
答案 1 :(得分:0)
我找到了一个解决方案:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is Enum)) return value;
return Enum.IsDefined(value.GetType(), value) ? value : System.Convert.ToInt32(value);
}