2016-07-12 83 views
0

我有一個Datagrid,它使用ResourceDictionary來定義它的樣式。從視圖模型更改xaml資源字典中系統變量的值mvvm

<DataGrid Style="{StaticResource HistoryViewDataGridStyle}" .....> 
</DataGrid> 

而在ResourceDictionary中我有下面定義的樣式。

<Style TargetType="{x:Type DataGrid}" x:Key="HistoryViewDataGridStyle"> 
    <Style.Resources> 
     <Style TargetType="{x:Type DataGridCell}"> 
      <Setter Property="Foreground" Value="Black" /> 
      <Setter Property="FontWeight" Value="Normal"/> 
      <Setter Property="FontSize" Value="11"/> 
      <Setter Property="Height" Value="30"/> 
      <Setter Property="BorderBrush" Value="Transparent" /> 
      <Setter Property="BorderThickness" Value="0"/>..... 

現在我想爲DataGrids使用應用程序寬度的字體顏色和字體大小,用戶可以在其中更改值。 我正在使用mvvm模型,並設法爲用戶提供顏色和字體大小的下拉列表。

我要尋找一個在資源字典中使用的系統變量的方法,

<sys:Double x:Key="DFontSize">12</sys:Double> 
<SolidColorBrush x:Key="FontColorBrush" Color="Black"/> 

<Style TargetType="{x:Type DataGrid}" x:Key="HistoryViewDataGridStyle"> 
    <Style.Resources> 
     <Style TargetType="{x:Type DataGridCell}"> 
      <Setter Property="Foreground" Value=**FontColorBrush** /> 
      <Setter Property="FontSize" Value=**DFontSize**/> 

有沒有辦法,我可以從後面的代碼設置值,這些系統變量並相應地更改數據網格樣式的一種方式。

請評論你的建議。

感謝 Mathee

+0

你可以用動態的資源做到這一點。 [這個答案](http://stackoverflow.com/questions/37396964/how-can-i-add-a-binding-to-a-resource-dictionary/37416464#37416464)可能會幫助你。 – Matas

+0

是否必須將resourceDictionary中的setter值和Datagrid樣式都設置爲Dynamic Resources。這樣做時我得到了cast無效的錯​​誤 – Mathee

回答

0

這取決於你是否要保存這些新設置或不?

如果是,那麼你必須使用Application Settings。右擊「項目」>「屬性」>「設置」,然後創建類型爲System.Windows.Style(PresentationFramework.dll程序集)的設置。

如果不是,則使用DynamicResource綁定而不是StaticResource

Settings class in C# (Codeproject)

How to create Application Settings

Using Settings in C#

+0

是否必須將resourceDictionary中的setter值和Datagrid樣式都設置爲Dynamic Resources。當我這樣做的時候我得到了無效的錯誤 – Mathee

+0

而且我想在用戶從下拉列表中選擇時立即改變樣式。我們可以用這種方式來使用它嗎? – Mathee