2

我正在尝试为组合框编写一个简单的附加属性,该属性通过回调更改组合框的数据源我的问题是回调函数不适用于默认值,这是我的代码

附属性类

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" />

4

1 回答 1

4

只有在属性实际更改时才会调用回调。最初它有它的默认值,并且根据设计不会调用回调。所以你要么需要手动调用它,要么你可以使用类型的属性Types?(使其可以为空)手动让默认值为null

public static readonly DependencyProperty TypeOfProperty =
            DependencyProperty.RegisterAttached(
                "TypeOf", 
                typeof(Types?), 
                typeof(ComboBoxAttached), 
                new PropertyMetadata(null, OnTypesChanged)); 
于 2012-10-15T09:13:53.480 回答