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
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
<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?(make it nullable) hand let the default value benull: