我會傾向於這樣處理:
- 使每個網格顏色單獨的資源,然後使用DynamicResource從網格樣式引用它們。
- 在一個單獨的「顏色」資源字典你Styles.xaml內把這些(下ResourceDictionary.MergedDictionaries)
- 定義具有顏色屬性,如果設置,更新畫筆的顏色在ResourceDictionary中
一個ColorProxy對象
- 在設置頁面的構造函數中,克隆「顏色」ResourceDictionary併爲每種顏色構造一個ColorProxy,然後綁定它們
- 在設置頁面的「保存」按鈕中,將「顏色」ResourceDictionary複製到您的用戶設置存儲並且也轉換爲主「顏色」ResourceDictionary
大部分都很簡單,所以我不會詳細討論。
這裏是Styles.xaml的想法:
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<SolidColorBrush x:Key="Row Background Color" Color="..." />
...
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="DataGrid">
...
<Setter Property="Background" Value="{DynamicResource Row Background Color}" />
...
</Style>
</ResourceDictionary>
這裏的代碼複製結構的ColorProxy對象:
public IEnumerable<ColorProxy> ColorProxies
{
get
{
return
from key in _colorDict.Keys
select new ColorProxy { Dictionary=_colorDict, Key=key };
}
}
和ColorProxy本身:
public class ColorProxy
{
public ResourceDictionary Dictionary { get; set; }
public object Key { get; set; }
public Color Value
{
get { return ((SolidColorBrush)Dictionary[Key]).Color; }
set { Dictionary[Key] = new SolidColorBrush { Color = value }; }
}
}
的現在可以使用以下編輯ResourceDictionary中的顏色:
<ItemsControl ItemsSource="{Binding ColorProxies}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="local:ColorProxy">
<DockPanel>
<TextBlock Text="{Binding Key}" Width="200" />
<ColorPicker Color="{Binding Color}" />
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
已編輯的ResourceDictionary可以轉換爲字符串存儲使用XamlWriter和使用XamlReader重新加載。
由Styles.xaml生成的主ResourceDictionary中的MergedDictionaries集合可以通過調用舊字典上的.Remove()和新字典上的.Add()來修改。
ResourceDictionaries可以通過簡單地構造一個新的ResourceDictionary來克隆,這個ResourceDictionary迭代舊字典中的條目並將它們添加到新字典中。
該技術不需要限於編輯顏色。可以創建任何類型的代理對象,包括通用綁定中的轉換器處理數據轉換的對象。