我有以下来自ComboBox
的自定义用户控件:
public class EnumSourceComboBox : ComboBox
{
public static readonly DependencyProperty ExcludedItemsProperty =
DependencyProperty.Register(
"ExcludedItems",
typeof(IList),
typeof(EnumSourceComboBox),
new PropertyMetadata(
new List<object>()));
public EnumSourceComboBox()
{
this.ExcludedItems = new List<object>();
}
public IList ExcludedItems
{
get
{
return (IList)this.GetValue(EnumSourceComboBox.ExcludedItemsProperty);
}
set
{
this.SetValue(EnumSourceComboBox.ExcludedItemsProperty, value);
}
}
}
我在XAML
中使用它如下:
<controls:EnumSourceComboBox>
<controls:EnumSourceComboBox.ExcludedItems>
<employeeMasterData:TaxAtSourceCategory>FixedAmount</employeeMasterData:TaxAtSourceCategory>
<employeeMasterData:TaxAtSourceCategory>FixedPercentage</employeeMasterData:TaxAtSourceCategory>
</controls:EnumSourceComboBox.ExcludedItems>
</controls:EnumSourceComboBox>
这构建良好,没有XAML
解析异常或类似的东西。但是,ExcludedItems
始终有count == 0
,因此XAML
中定义的两个项目不会添加到列表中。
如何定义依赖项属性以支持此行为?
更新:这里是TaxAtSourceCategory
枚举:
public enum TaxAtSourceCategory
{
/// <summary>
/// The none.
/// </summary>
None,
/// <summary>
/// The fixed amount.
/// </summary>
FixedAmount,
/// <summary>
/// The fixed percentage.
/// </summary>
FixedPercentage,
// Has some more values, but I don't think that matters
}
答案 0 :(得分:1)
@cguedel,
我尝试了你的DependencyProperty代码,运行正常。
我在属性的XAML内容中添加了两个字符串,而不是TaxAtSourceCategory
个实例
在窗口的Loaded事件中,我计算了2的列表。
所以你可能与TaxAtSourceCategory
课程有关。
也许你可以显示TaxAtSourceCategory
代码,检查构造函数调用...
此致
答案 1 :(得分:1)
在下面的代码中,有一个EnumSourceCombobox跟踪集合中的变化
有跟踪:
- 收集更改(收集更换为另一个)
- 和集合中的更改(添加/删除/清除)
public class EnumSourceComboBox : ComboBox
{
private ObservableCollection<TaxAtSourceCategory> previousCollection;
public static readonly DependencyProperty ExcludedItemsProperty =
DependencyProperty.Register(
"ExcludedItems",
typeof(ObservableCollection<TaxAtSourceCategory>),
typeof(EnumSourceComboBox),
new PropertyMetadata(null));
public ObservableCollection<TaxAtSourceCategory> ExcludedItems
{
get
{
return (ObservableCollection<TaxAtSourceCategory>)this.GetValue(EnumSourceComboBox.ExcludedItemsProperty);
}
set
{
this.SetValue(EnumSourceComboBox.ExcludedItemsProperty, value);
}
}
public EnumSourceComboBox()
{
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(EnumSourceComboBox.ExcludedItemsProperty, typeof(EnumSourceComboBox));
dpd.AddValueChanged(this, (o, e) =>
{
if (previousCollection != null)
previousCollection.CollectionChanged -= ExcludedItemsChanged;
previousCollection = ExcludedItems;
if (previousCollection != null)
previousCollection.CollectionChanged += ExcludedItemsChanged;
});
this.ExcludedItems = new ObservableCollection<TaxAtSourceCategory>();
}
void ExcludedItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Take into account change in the excluded items more seriously !
MessageBox.Show("CollectionChanged to count " + ExcludedItems.Count);
}
}
以下是解决方案的链接: http://1drv.ms/1P8cMVc
最好用