2016-07-12 33 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