我正在尝试为组合框编写一个简单的附加属性,该属性通过回调更改组合框的数据源我的问题是回调函数不适用于默认值,这是我的代码
附属性类
namespace WpfApplication2
{
public enum Types { Employee, Position, Task }
public class ComboBoxAttached:DependencyObject
{
public static readonly DependencyProperty TypeOfProperty =
DependencyProperty.RegisterAttached(
"TypeOf",
typeof(Types),
typeof(ComboBoxAttached),
new PropertyMetadata(Types.Position, OnTypesChanged));
public static void SetTypeOf(DependencyObject d, Types use)
{
d.SetValue(TypeOfProperty, use);
}
private static void OnTypesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ComboBox cb = d as ComboBox;
// MessageBox.Show(((Types)e.NewValue).ToString());
switch ((Types) e.NewValue)
{
case Types.Employee:
cb.ItemsSource = SourceData.Employee;
break;
case Types.Position:
cb.ItemsSource = SourceData.Position;
break;
case Types.Task:
cb.ItemsSource = SourceData.Task;
break;
}
}
}
}
数据源类别
namespace WpfApplication2
{
public static class SourceData
{
public static List<string> Employee=new List<string>(){ "Manager","HR","CEO","CFO"};
public static List<string> Position = new List<string>() { "Right", "Left", "Forward", "Backward" };
public static List<string> Task = new List<string>() { "Assessment", "Measurement", "Consult", "Other" };
}
}
xml
<ComboBox MyProp:ComboBoxAttached.TypeOf="Position" Margin="5" />