资源中的ElementName绑定在与DynamicResource一起使用时失败,但与StaticResource一起使用

时间:2014-10-28 13:52:10

标签: wpf vb.net xaml binding staticresource

在WPF UserControl中,我将Resources部分中Color的{​​{1}}属性绑定到UserControl上的依赖项属性。 如果我使用SolidColorBrushSolidColorBrush一切正常,但是如果我尝试使用StaticResource,则绑定会失败并显示错误。虽然我可以通过使用至少一个StaticResource来引用DynamicResource来解决这个问题,但我想知道为什么它会这样做以提高我对WPF的理解。

这里是UserControl xaml,codebehind和error ...

SolidColorBrush
<UserControl x:Class="TestUserControl"
                x:Name="MyUserControl"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <SolidColorBrush x:Key="BrushKey" Color="{Binding ElementName=MyUserControl,Path=TestProp}"></SolidColorBrush>
    </UserControl.Resources>
    <StackPanel>
        <TextBlock Background="{DynamicResource BrushKey}">Foo</TextBlock>
        <!-- Uncommenting this makes everything work, including the DynamicResource reference. -->
        <!--<TextBlock Background="{StaticResource BrushKey}">Bar</TextBlock>-->
    </StackPanel>
</UserControl>  
Public Class TestUserControl

    Public Property TestProp As Color
        Get
            Return GetValue(TestPropProperty)
        End Get

        Set(ByVal value As Color)
            SetValue(TestPropProperty, value)
        End Set
    End Property

    Public Shared ReadOnly TestPropProperty As DependencyProperty = DependencyProperty.Register("TestProp",
                                                                                                GetType(Color),
                                                                                                GetType(TestUserControl),
                                                                                                New PropertyMetadata(Color.FromRgb(&H0, &HBC, &HC4)))

End Class

0 个答案:

没有答案