2016-02-09 40 views
0

我有一個簡單的UWP應用程序一個簡單的計算器。所以我通過這樣的風格設置了按鈕的所有屬性。用按鈕更改C#資源值

<Page.Resources> 
    <Style TargetType="Button" x:Key="CalculatorButtons"> 
     <Setter Property="VerticalAlignment" Value="Stretch" /> 
     <Setter Property="HorizontalAlignment" Value="Stretch" /> 
     <Setter Property="FontSize" Value="30" /> 
     <Setter Property="BorderThickness" Value="1" /> 
     <Setter Property="BorderBrush" Value="Black" /> 
     <Setter Property="Background" Value="AntiqueWhite" /> 
    </Style> 
</Page.Resources> 

我想製作一個按鈕,它將更改我所做的樣式中背景屬性的值。我的按鈕代碼開始這樣

private void ColorChange_Click(object sender, RoutedEventArgs e) 
{ 

} 

我在這個新的,我不能找到一種方法來訪問它,它從這裏改變。

回答

0

好了,所以很多搜索後,我發現一切我需要在這裏http://blog.jerrynixon.com/2013/01/walkthrough-dynamically-skinning-your.html的想法是非常簡單的。所以從我的風格,我刪除了背景設置和這樣做自己的資源。但是在我自己的詞典中,我將其命名爲Style.Blue.xaml,因爲它的藍色我爲我所有的顏色做過,像傑里尼克鬆說的那樣。

<SolidColorBrush x:Key="ButtonColor" Color="Blue" /> 

,我會用這條線

Background="{StaticResource ButtonColor}" 

後,我在我的按鈕MainPage.xaml.cs中創建這種訪問它在我的按鈕。

void ChangeTheme(Uri source) 
    { // Recreated my Merged dictinaries at the app.xaml 

     var _Custom = new ResourceDictionary { Source = source }; 
     var _Main = new ResourceDictionary { MergedDictionaries = { _Custom } }; 
     App.Current.Resources = _Main; 


     // This is needed to basiclly Refresh the page since we use Static Resources. 
     // so we navigate forth and back to the whole frame. 

     var _Frame = Window.Current.Content as Frame; 
     _Frame.Navigate(_Frame.Content.GetType()); 
     _Frame.GoBack(); 
    } 

然後我加入這個代碼上的每個按鈕,只是改變取決於我想要的顏色的來源(如果我想藍色的是 - > Style.Blue.xaml紅 - > Style.Red.xaml)和ms-appx:/ StyleColors /是路徑。我爲我的所有風格製作了一個文件夾。

private void ColorChange_Click(object sender, RoutedEventArgs e) 
     { 
      ChangeTheme(new Uri("ms-appx:/StyleColors/Style.Blue.xaml")); 
     } 

現在用一行代碼我可以改變我需要的所有按鈕或其他類型的數據的顏色。

我希望它也能幫助更多的人。

0

您無法在運行時修改樣式,唯一的方法是創建新樣式並替換舊樣式。

private void ColorChange_Click(object sender, RoutedEventArgs e) 
{ 
     var style = new Style(typeof(Button)); 

     style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Stretch)); 
     style.Setters.Add(new Setter(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Stretch)); 
     style.Setters.Add(new Setter(Control.FontSizeProperty, 30.0)); 
     style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(1.0))); 
     style.Setters.Add(new Setter(Control.BorderBrushProperty, Brushes.Black)); 

     style.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Orange)); 

     this.Resources["CalculatorButtons"] = style; 
} 

請注意,您在這種情況下,使用DynamicResource,例如:

<Button Style="{DynamicResource ResourceKey=CalculatorButtons}" ... 
+0

好吧,我看到但在UWP中,我無法使用DynamicResource,這是從視覺工作室告訴我的。 該職位已改爲WPF sry,所以我唯一的選擇是編寫一個代碼,將單獨更改每個按鈕我猜,因爲我不能使用此代碼! – panoukos41

+0

您可以使用此方法解決UWP http://stackoverflow.com/a/33168813/5574010 –