ElementName binding in resources does not work when used with DynamicResource, but works with StaticResource
In WPF UserControl, I bind an Color
item property SolidColorBrush
in Resources to a dependency property in UserControl. If I use SolidColorBrush
with StaticResource
, everything works fine, however, if I try to use DynamicResource
, the communication fails with an error. While I can work around the problem by using at least one StaticResource to reference SolidColorBrush
, I want to know why it behaves in such a way as to improve my understanding of WPF.
Here's UserControl xaml, codebehind and error ...
<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
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=MyUserControl'. BindingExpression:Path=TestProp; DataItem=null; target element is 'SolidColorBrush' (HashCode=29677729); target property is 'Color' (type 'Color')
source to share
No one has answered this question yet
Check out similar questions: