将枚举绑定到代码中的XAML


public enum Type
{
One = 1,
Two = 2,
Three = 3
}
public void Method()
{
Type type = Type.One;
var binding = new Binding(type - ???);
binding.Converter = ?????;
var child = new FrameworkElementFactory(typeof(ComboBox));
child.SetValue(ComboBox.ItemsSourceProperty, Enum.GetValues(typeof(Type)));
child.SetValue(ComboBox.SelectedValueProperty, binding);
}

我想在代码中将type绑定到XAML。但我不知道该怎么做,也不知道转换器(Enum<->String(的名称。我只知道它是标准转换器。

问题:

  1. 我该怎么做
  2. 在哪里可以找到所有标准转换器的列表

将绑定的Source设置为要绑定的对象。如果对象实现INotifyPropertyChanged,则使用Path侦听特定属性,并在设置属性时引发属性更改事件。

我不确定是否有标准的枚举到字符串转换器,尽管您可以在绑定上使用StringFormat或实现自定义转换器。有一些基于DependencyProperty的自动类型转换,你将其绑定到它上,所以你甚至可能不需要它

您可以在这里找到作为接口派生类型的"标准"转换器的列表。https://learn.microsoft.com/en-gb/dotnet/api/system.windows.data.ivalueconverter?view=netframework-4.7.2

您还需要使用SetBinding来实际设置DependencyObjectDependencyProperty上的绑定。看见https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-create-a-binding-in-code

最新更新