【问题标题】:How can I bind a background color in WPF dynamically?如何在 WPF 中动态绑定背景颜色?
【发布时间】:2016-12-16 06:28:08
【问题描述】:

我无法动态绑定背景,因为它引发异常“无法在“Binding”类型的“源”属性上设置“DynamicResourceExtension”。“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>

【问题讨论】:

  • 你应该更好地使用 MVVM 结构的绑定

标签: wpf xaml data-binding


【解决方案1】:

更新您的绑定以从您的 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 就可以了(在编译期间会应用画笔)。

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多