使用复选框或文本框作为枚举类型

如果我有这个结构:

public class Parent { public string Name{get; set;} public List Childs {get; set;} } public class Child { public string Name{get; set;} public string Value{get; set;} public enum ValueType {get; set;} } public enum ValueType { Int, Boolean, String }; public class ParentFactory { public List Parents {get; set;} public ParentFactory() { Child child1 = new Child() {Name="Filter1", Value="1", ValueType=ValueType.String}; Child child2 = new Child() {Name="isExecuted", Value="true", ValueType=ValueType.Boolean}; Child child3 = new Child() {Name="Width", Value="10", ValueType=ValueType.Int}; Parent parent1 = new Parent(){Name="Adam", Childs = new List(){child1, child2}}; Parent parent2 = new Parent(){Name="Kevin", Childs = new List(){child3}}; Parents = new List(){parent1, parent2}; } } 

我想绑定对象: ParentFactory parentFactory = new ParentFactory()到ItemsControl:

                     

在Stackpanel中,有一个控件:TextBox。 但是,我希望它更具动态性:如果ValueType是布尔值,则使用复选框,否则使用文本框:

这是可能的,如果可以的话,我该如何实现呢?

我认为最简单的方法是在面板中同时使用它们并定义两个新的布尔属性,这些属性将通过Boolean To Visibility ValueConverter控制它们的Visibility性。

 public bool IsValueTypeBoolean { get { ...Conditions that will return true for CheckBox. } } public bool IsValueTypeOther { get { return !this.IsValueBoolean; } }   

Boolean到VisibilityConverter

 [ValueConversion(typeof(bool), typeof(Visibility))] public class BooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool myValue = (bool)value; if (myValue) return Visibility.Visible; else return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

将此作为资源添加到您的XAML:

   

我希望没有错别字……

您可以动态更改DataTemplate

XAML

      // Do you binding    // Do you binding          

确保正确设置Bindings …并为Condition1Condition2创建DataTemplates

希望能帮助到你 :)