如何动态绑定WPF中的背景颜色?

时间:2016-12-16 06:28:08

标签: wpf xaml data-binding

我无法动态绑定背景,因为它会引发异常" A' DynamicResourceExtension'不能在“来源”上设置属性类型'绑定' A' DynamicResourceExtension'只能在DependencyObject的DependencyProperty上设置。"

<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 个答案:

答案 0 :(得分:2)

更新绑定以从DynamicResource和StaticResource声明中删除'Binding'关键字。

更新至:

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

注意:

你应该在这里只使用StaticResource,因为它似乎没有在运行时更改背景颜色。 DynamicResource通常用于在第一次访问资源时在运行时动态加载资源,或者如果要进行运行时切换(即主题/主题切换)。如果您只使用一次,StaticResource就可以了(刷子将在编译期间应用)。

相关问题