2016-07-01 70 views
0

我在App.xaml中一個SolidColorBrush資源這樣的:在資源字典改變的SolidColorBrush#顏色失敗:屬性爲只讀

<SolidColorBrush Color="#73AF00" x:Key="BaseGreen"></SolidColorBrush> 

我的所有樣式(按鈕,網格背景和顏色,等等,等等)含有該資源,我希望當用戶更改顏色設置時,整個應用顏色將變爲藍色。

var color = System.Windows.Application.Current.Resources["BaseGreen"] as SolidColorBrush; 
       color.Color = Color.FromRgb(41, 128, 185); 

I try what this answer suggest但是當我指定值,一個例外是拋出:

This property is set to read only and cannot be set 

我也嘗試,但沒有happended:

var color = this.TryFindResource("BaseGreen") as SolidColorBrush; 
color = new SolidColorBrush(Color.FromRgb(41, 128, 185)); 

有沒有辦法,我失去了一些東西?

+1

這將是預期的行爲。你應該交換資源,而不是屬性。在同一個資源字典或其他資源中交換資源字典或其他資源。有很多關於動態主題的精彩文章,人們在這裏花了很多時間,這將更詳細地解釋。 –

回答

0

如果你想爲你的SolidColorBrush動態設置顏色App.xaml,那麼你不應該設置顏色的值:你應該通過DynamicResource綁定

<Application.Resources> 
    <SolidColorBrush x:Key="DynamicColor" /> 
</Application.Resources> 

而在你的控制:

<Label Name="MyLabel" 
      Content="Hello" 
      Background="{DynamicResource Color}" /> 

    <Button Content="Change color" 
      Width="100" 
      Height="30" 
      Click="Button_Click" /> 
</Grid> 

然後要更改Resource您應該:

Application.Current.Resources["YourResource"] = YourNewValue; 

讓我給個例子:

private void Window_ContentRendered(object sender, EventArgs e) 
{ 
    SolidColorBrush YourBrush = Brushes.Green; 

    // Set the value 
    Application.Current.Resources["DynamicColor"] = YourBrush;   
} 

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    SolidColorBrush YourBrush = Brushes.Orange; 

    // Set the value 
    Application.Current.Resources["DynamicColor"] = YourBrush; 
} 

DynamicResources用於改變。在哪裏改變 - 這是開發者的願望。