http://www.dotnetfunda.com/articles/article961-wpf-tutorial--dependency-property-.aspx
我已經創建了我的用戶是這樣的:
用戶控件XAML:
<UserControl x:Class="PLVS.Modules.Partner.Views.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tp="http://thirdparty.com/controls"
x:Name="UC">
<tp:ContainerControl x:Name="tpControl">
<tp:ContainerControl.Items>
<tp:SomeItem SomeProperty="SomeValue">
<TextBlock Text="SomeText"/>
</tp:SomeItem>
</ig:TabItemEx>
</tp:ContainerControl.Items>
</tp:ContainerControl>
</UserControl>
用戶控件的代碼隱藏:
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
SetValue(TestItemsPropertyKey, new ObservableCollection<ThirdPartyClass>());
}
public ObservableCollection<ThirdPartyClass> TestItems
{
get
{
return (ObservableCollection<ThirdPartyClass>)GetValue(TabItemsProperty);
}
}
public static readonly DependencyPropertyKey TestItemsPropertyKey =
DependencyProperty.RegisterReadOnly("TestItems", typeof(ObservableCollection<ThirdPartyClass>), typeof(TestControl), new UIPropertyMetadata(new ObservableCollection<ThirdPartyClass>(), TestItemsChangedCallback));
public static readonly DependencyProperty TestItemsProperty = TestItemsPropertyKey.DependencyProperty;
private static void TestItemsChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
TestControl ib = obj as TestControl;
var newNvalue = e.NewValue; // Why is e.NewValue null???
}
}
我想在以後使用這樣的用戶控件:
<localControl:TestControl x:Name="testControl">
<localControl:TestControl.TabItems>
<tp:SomeItem SomeProperty="SomeValue">
<TextBlock Text="SomeText2"/>
</tp:SomeItem>
<tp:SomeItem SomeProperty="SomeValue">
<TextBlock Text="SomeText3"/>
</tp:SomeItem>
</tp:ContainerControl.Items>
</localControl:TestControl>
在上面的代碼中,我在我的用戶增加了一個回調函數,這樣我可以添加新的項目到容器控件「 tpControl「在xaml中聲明。但是,當回調函數被觸發時,新值爲空。這裏的問題是爲什麼?