文章目录
- 添加控件
 - 具体实现
 - 代码说明
 
txt阅读器系列:
- 需求分析和文件读写
 - 目录提取类💎列表控件与目录
 - 字体控件绑定
 - 书籍管理系统💎用树形图管理书籍
 
添加控件
除了字体、字体大小之外,文字和背景颜色也会影响阅读观感,其设置方法与选择字体如出一辙,都通过combobox控件来选择。故而在阅读设置里面添加
<StackPanel x:Name="color" Orientation="Horizontal">
    <TextBlock Text="前景"/>
    <ComboBox x:Name="cbForeColor" Width="105"/>
    <TextBlock Text="背景"/>
    <ComboBox x:Name="cbBgColor" Width="105"/>
</StackPanel>
 
具体实现
考虑到C#中封装的大多数颜色,其实我们都不太认识,为了更加直观,故而在ComboBox中的每个选项都赋上对应的颜色,其对应的C#代码为
using System.Reflection;
public void init()
{
    foreach (var fm in Fonts.SystemFontFamilies)
        cbFont.Items.Add(fm.Source);
    cbFont.SelectedIndex = 0;
    var cs = typeof(Brushes)
        .GetProperties(BindingFlags.Static | BindingFlags.Public)
        .Select(x => x.Name )
        .ToArray();
    int i;
    int iWhite = Array.IndexOf(cs, "White");
    int iBlack = Array.IndexOf(cs, "Black");
    cbForeColor.ItemsSource = cs.Select(
        x => new ComboBoxItem { Content = x });
    cbForeColor.SelectedIndex = iBlack;
    cbBgColor.ItemsSource = cs.Select(
        x => new ComboBoxItem { Content = x });
    cbBgColor.SelectedIndex = iWhite;
    var bc = new BrushConverter();
    foreach (ComboBoxItem item in cbForeColor.Items)
        item.Background = (SolidColorBrush)bc.ConvertFromString(
            item.Content.ToString());
    
    foreach (ComboBoxItem item in cbBgColor.Items)
        item.Background = (SolidColorBrush)bc.ConvertFromString(
            item.Content.ToString());
}
 
代码说明
其中,typeof(Brushes).GetProperties是C#的反射功能,可以返回某个类的所有属性。其中BindingFlags.Static | BindingFlags.Public表示只返回静态公共属性。
然后调用Select,提取出这些属性的Name,最后将其转为数组,赋值给cs。
由于想为ComboBox中的每一项都填上不同的颜色,而字符串本身并没有颜色这个属性,所以不能直接将ItemsSource设置为cs,而要将所有字符串封装在ComboBoxItem中。
然后,遍历这些ComboBoxItem,将其背景色设置为其名字对应的颜色。
最后,修改txt控件的前景色和背景色,在xaml代码中加入
Foreground="{Binding SelectedItem.Content, ElementName=cbForeColor}"
Background="{Binding SelectedItem.Content, ElementName=cbBgColor}"
 
效果如下



















