gpt4 book ai didi

c# - 附加属性回调不适用于 wpf VS2012 中的默认值

转载 作者:行者123 更新时间:2023-11-30 21:03:25 27 4
gpt4 key购买 nike

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

附加属性类

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

xaml

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

最佳答案

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

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

关于c# - 附加属性回调不适用于 wpf VS2012 中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12892209/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com