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



i不能动态绑定背景,因为它会引起异常。依赖项的依赖关系。"

<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>

更新绑定以从您的DynamicResource和staticResource声明中删除'绑定'关键字。

更新到:

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

注意:

您可能应该在此处仅使用staticresource,因为看来您在运行时没有更改背景颜色。DynamicResource通常用于在第一次访问运行时在运行时动态加载资源,或者如果要进行运行时切换(即主题/主题切换)。如果您简单地使用一次,那么静电是可以的(刷子将在编译时间内应用)。

最新更新