2

我正在创建一个 WinRT CustomControl,它具有 PropertyChangedCallback 的依赖属性。在该回调方法中,我尝试在使用 GetTemplateChild() 方法从 OnApplyMethod 检索的控件的某些部分上设置值。

问题是在 OnApplyTemplate 之前调用了 PropertyChangedCallback,因此控制部分仍然为空。

我发现的一种解决方法是我在自定义控件的加载事件中调用此 DP。在那种情况下,一切对我来说都很好。但每一种情况都不适用。假设如果有人想通过 xaml 绑定值,问题又会出现。

是否有人对此问题有任何永久解决方法。

4

1 回答 1

4

当我想做你所描述的事情时,这是我遵循的一般模式:

private void OnFooChanged(...)
{
    if (someNamedPart != null && someOtherNamedPart != null && ...)
    {
        // Do something to the named parts that are impacted by Foo 
        // when Foo changes.
    }
}

private void FooChangedCallback(...)
{
    // Called by WinRT when Foo changes
    OnFooChanged(...)
}

protected override void OnApplyTemplate(...)
{
    // Theoretically, this can get called multiple times - every time the 
    // consumer of this custom control changes the template for this control.
    // If the control has named parts which must react to the properties
    // this control exposes, all that work must be done here EVERY TIME
    // a new template is applied.

    // Get and save named parts as local variables first

    OnFooChanged(...)
}

希望伪代码有所帮助!

于 2014-01-25T04:41:58.667 回答