简体   繁体   English

附加的属性回调不适用于WPF VS2012中的默认值

[英]Attached property call back doesn't work with default value in wpf VS2012

I'm trying to write a simple attached property for a combobox which changes the data source of a combobox via a callback my problem is that the call back function DOESN'T work for the defualt value , here is my code 我正在尝试为组合框编写一个简单的附加属性,该属性通过回调更改组合框的数据源。我的问题是,回调函数对defualt值无效,这是我的代码

Attached proprty class 附属财产阶级

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;
            }
        }
    }
 }

the class of data source 数据源类别

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" };  
    }
}

xaml XAML

<ComboBox MyProp:ComboBoxAttached.TypeOf="Position" Margin="5" />

The callback will only be called when the property actually changes. 仅在属性实际更改时才调用回调。 Initially it has its default and by design the callback will not be called. 最初,它具有默认值,并且根据设计,该回调将不会被调用。 Sou you will either need to call that manually or you could use a property of type Types? 这样您要么需要手动调用它,要么可以使用Types?的属性Types? (make it nullable) hand let the default value be null : (使其变为可为空)手将默认值设为null

public static readonly DependencyProperty TypeOfProperty =
            DependencyProperty.RegisterAttached(
                "TypeOf", 
                typeof(Types?), 
                typeof(ComboBoxAttached), 
                new PropertyMetadata(null, OnTypesChanged)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM