初始化组件后未设置wpf属性

时间:2013-04-28 14:52:55

标签: wpf user-controls dependency-properties

我遇到有关xaml中设置的属性的问题 我用依赖属性'MidiChanel'创建了一个用户控件 我在xaml中将此属性的值设置为10。 在用户控件的构造函数中,我需要此值将其添加到字典中并将值传递给我的用户控件的子类。

问题是,在构造函数中,即使在调用initializecomponents之后,属性stil也有其默认值,而不是在xaml中设置的值。 事实上,它根本没有设定。

如果我将'MidiChanel'属性更改为普通属性,则值将被设置,但它不是初始化userControl的组件,该组件设置值,但初始化主窗口的组件。 调用stack = Main.InitializeComponents,userControl的构造函数(值尚不可用),'MidiChanel'的Setter被设置。 (由谁?,调用堆栈说Main.InitializeComponents)。

我是一名winforms开发者,发现这一切都很奇怪。 在Main.InitializeComponents之后,我可以遍历主页面中的所有userControl,并在这里做所有事情,但这似乎是一件奇怪的事情。

这里有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以设置一个在您的dependenyProperty更改时引发的回调方法

   public int SomeProp
    {
        get { return (int)GetValue(SomePropProperty); }
        set { SetValue(SomePropProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SomeProp.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SomePropProperty =
        DependencyProperty.Register("SomeProp", typeof(int), typeof(yourOwnerclass), new PropertyMetadata(new PropertyChangedCallback(OnSomePropertyChnaged)));

    public static void OnSomePropertyChnaged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        (d as yourOwnerclass).SomeFunction();
    }