开发者

WPF UserControl event called only once?

I 开发者_如何学编程need to bind two-way a property of a user control to a property of a containing user control. I also need to set a default value to the property from code in the child (cannot be done easily from XAML tags).

If I call my code from the child constructor, the value is set in the parent but the change callback routine is not triggered (my understanding is that the parent doesn't yet exist at the time the child is created).

My current workaround is to catch the Loaded event of the child and to call the code from the handler. Howver as Loaded is called more than once, I need to set a flag to set the property only the first time. I don't like this way, but I don't know if there is a single shot event that could be used, or if this can be done otherwise. Any feedback based on your experience?


For the default value use the DependencyProperty and pass in FrameworkPropertyMetadata object containing the default value, e.g.

    public static readonly DependencyProperty ProductNameProperty =
            DependencyProperty.Register(
                "ProductName",
                typeof(string),
                typeof(ProductTextBox),
                new FrameworkPropertyMetadata(null, // Default Value
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                    new PropertyChangedCallback(ChangeProductName)) );

If the default value is variable per instance and differs then maybe a combination of

SetValue(ProductNameProperty, value_required); 
PropertyChanged(this, new PropertyChangedEventArgs("ProductName")); 

Possibly both in the constructor or send the PropertyChanged in the loaded event if it doesn't work in the constructor. I've not actually tried this...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜