WPF枚举指定类型控件

22 篇文章 2 订阅
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}


foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
    // do something with tb here
}
public static IEnumerable<T> FindLogicalChildren<T> (DependencyObject depObj)where T: DependencyObject
{
      if (depObj != null)
      {
          foreach (object rawChild in LogicalTreeHelper.GetChildren(depObj))
          {
              if (rawChild is DependencyObject)
              {
                  if (rawChild is T)
                  {
                      yield return (T)rawChild;
                  }

                  foreach (T childOfChild in FindLogicalChildren<T>((DependencyObject)rawChild))
                  {
                      yield return childOfChild;
                  }
              }
          }
      }
  }

摘自https://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type

WPF中,我们可以使用ComboBox控件来显示枚举类型的值。以下是实现方法: 1. 定义一个枚举类型。 ``` public enum Gender { Male, Female, Unknown } ``` 2. 在XAML中定义ComboBox控件。 ``` <ComboBox Name="cmbBox" ItemsSource="{Binding Source={x:Static local:MainWindow.GenderEnumValues}}" /> ``` 3. 在代码中,定义一个静态属性,用于获取枚举类型的值。 ``` public static IEnumerable<Gender> GenderEnumValues { get { return Enum.GetValues(typeof(Gender)).Cast<Gender>(); } } ``` 4. 在代码中,将数据源绑定到ComboBox控件上。 ``` cmbBox.DataContext = this; ``` 通过以上步骤,就可以将ComboBox控件枚举类型绑定,并以下拉列表的形式显示枚举类型的值了。如果需要在ComboBox中显示枚举类型的名称,可以在XAML中设置DisplayMemberPath属性: ``` <ComboBox Name="cmbBox" ItemsSource="{Binding Source={x:Static local:MainWindow.GenderEnumValues}}" DisplayMemberPath="Name" /> ``` 其中,Name是枚举类型的名称。需要在枚举类型中定义Name属性: ``` public enum Gender { [Description("男")] Male, [Description("女")] Female, [Description("未知")] Unknown } public static string GetName(this Enum value) { var type = value.GetType(); var field = type.GetField(value.ToString()); var attr = field.GetCustomAttribute<DescriptionAttribute>(); return attr != null ? attr.Description : value.ToString(); } public string Name { get { return this.GetName(); } } ``` 这样就可以在ComboBox中显示枚举类型的名称了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sdhongjun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值