2016-12-16 40 views
0

我無法動態綁定背景,因爲它會引發異常「A'DynamicResourceExtension'不能在'Binding'類型的'Source'屬性上設置。'DynamicResourceExtension'只能在DependencyObject的DependencyProperty上設置。如何動態綁定WPF中的背景顏色?

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

+0

您應該更好地使用MVVM結構的綁定 – Ugur

回答

2

更新您結合您的DynamicResource和StaticResource的聲明中刪除 '綁定' 關鍵字。

更新到:

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

注:

你或許應該只使用靜態資源在這裏,因爲它似乎沒有更改在運行時的背景顏色。 DynamicResource通常用於在運行時第一次訪問資源期間動態加載資源,或者如果您想要執行運行時切換(即主題/主題切換)。如果你只使用它一次,StaticResource就好了(刷子將在編譯期間被應用)。

相關問題