0

I cannot bind the background dynamically because it raises exception " A 'DynamicResourceExtension' cannot be set on the 'Source' property of type 'Binding'. A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject."

<Window x:Class="TestWpfApplication.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpfApplication"
    mc:Ignorable="d"
    Title="Window2" Height="300" Width="300">
<Window.Resources>
    <SolidColorBrush Color="Blue" x:Key="customColorBrush"/>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button Background="{Binding Source={DynamicResource customColorBrush}}" Margin="20"></Button>
    <Button Background="{Binding Source={StaticResource customColorBrush}}" Margin="20" Grid.Row="1" Click="Button_Click"></Button>
</Grid>

1
  • You should better use Bindings for MVVM structure Commented Dec 16, 2016 at 10:01

1 Answer 1

2

Update your binding to remove the 'Binding' keyword from your DynamicResource and StaticResource declaration.

Update to:

 <Button Background="{DynamicResource customColorBrush}" Margin="20"></Button>
 <Button Background="{StaticResource customColorBrush}" Margin="20" Grid.Row="1" Click="Button_Click"></Button>

Note:

You should probably use only StaticResource here, as it appears you are not changing the Background color during run-time. DynamicResource is typically used to dynamically load the resource during run-time during the first time it is accessed, or if you want to do run-time switching (i.e., theme/theme switching). If you simply using it once, StaticResource is just fine (the brush will get applied during compile time).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.