读取并预设颜色属性的组合框

本文关键字:组合 属性 颜色 读取 | 更新日期: 2023-09-27 18:01:12

在教程中,我有以下组合框:

<ComboBox Name="comboBox_warnColor" Margin="5,0,5,0" SelectionChanged="comboBox_warnColor_SelectionChanged">
        <ComboBox.ItemTemplate>
                <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                                <Rectangle Fill="{Binding Name}" Width="12" Height="12" Margin="0,2,5,2" />
                                <TextBlock Name="PART_ColorName" Text="{Binding Name}" />
                        </StackPanel>
                </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

我这样填充它:

comboBox_warnColor.ItemsSource = typeof(Colors).GetProperties();

我想将所选项目保存在文本文件中,以便以后再次将其加载到组合框中。

在这种情况下,我可以保存什么值来使用它对于默认定义的颜色,什么是好的ID值

SelectedIndex我找不到。

读取并预设颜色属性的组合框

您可以使用SelectedValuePathSelectedValue,如下所示:

<ComboBox SelectedValuePath="Name" SelectedValue="{Binding SelectedName}" Name="comboBox_warnColor" Margin="5,0,5,0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="{Binding Name}" Width="12" Height="12" Margin="0,2,5,2" />
                <TextBlock Name="PART_ColorName" Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

在代码背后:

public class VeryUnrefinedViewmodel
{
    public string SelectedName { get; set; }
}
// ...
VeryUnrefinedViewmodel _DataContextInstance = new VeryUnrefinedViewmodel();
// your initialization code
comboBox_warnColor.ItemsSource = typeof(Colors).GetProperties();
comboBox_warnColor.DataContext = _DataContextInstance;
// _DataContextInstance.SelectedName will contain the name of the selected color

您可以通过设置SelectedName的初始值以编程方式预先选择颜色。如果要动态更改选择,则需要为视图模型实现INotifyPropertyChanged

 VeryUnrefinedViewmodel _DataContextInstance = new VeryUnrefinedViewmodel() { SelectedName = "Yellow" };

RGBA可以在唯一模式下确定颜色,所以您可能希望将其存储为ID。你可以用这个问题将你的颜色转换为RGBA。