更改列表框中项的外观,而不更改/获取原始选定项值

本文关键字:获取 原始 列表 外观 | 更新日期: 2023-09-27 18:30:40

我以这种方式绑定ListBoxes Properties.Settings StringCollection

 <ListBox Height="52" HorizontalAlignment="Left" Margin="12,0,0,148" Name="FolderList" VerticalAlignment="Bottom" Width="120" ItemsSource="{Binding Source={x:Static properties:Settings.Default},Path=Folders}"/>

然后我意识到我不想显示 raw(因为它们是以 $ 结尾的隐藏共享文件夹)。我想在 ListBox 上以标题大小写显示它们并修剪最后一个美元符号,所以我实现了一个通过IValueConverter StringCollection

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    StringCollection raws = (StringCollection)value;
    StringCollection output = new StringCollection();
    foreach (string raw in raws)
    {
        bool hasDollar = false;
        if (raw.Last() == '$') hasDollar = true; 
        TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
        output.Add(hasDollar ? myTI.ToTitleCase(raw.Substring(0, raw.Length - 1))
            : myTI.ToTitleCase(raw));
    }
    return output;
}   

它有效。我的问题是:

当我执行button_click事件以获取 SelectedItem 时,获取原始(未转换)字符串的干净方法是什么?我可能可以直接访问属性,计算索引并进行比较,但可能有更干净的方法。

更改列表框中项的外观,而不更改/获取原始选定项值

有一种更简单的方法可以做到这一点,而无需编写自定义转换器来去除 1 个字符。看看我扔在一起的代码。这是seudo代码,但它应该给你一个想法。

FolderObject
{
    private string _name;
    public string name 
    { 
        get { return this._name; } 
        set
        {
            this._name = value.trim( new char[]{ '$' } )
        }
    }
    private string _raw;
    public string raw 
    { 
        get { return this._raw; }  
        set { this._raw = value; }
    }
}
class form1 : Form
{
    private List<FolderObject> _folders;
    private BindingSource _bindingSource;
    public form1()
    {
        Initialize();
    }
    public void Initialize()
    {
        _folders = new List<FolderObject>();
        _bindingSource = new BindingSource();
        List<FolderObject> folders = new List<FolderObject>();
        //Fill folders ...
        _bindingSource.DataSource = folders;
        //bind collection to listbox
        listbox1.DisplayMember = "Name";
        listbox1.ValueMember = "Raw";
        listbox1.DataSource = _bindingSource;
    }
    button1_Click(object sender, System.EventArgs e)
    {
        Console.WriteLine(string.format("Folder name is: {0}, Raw name is: {1}", listbox1.SelectedMember, listbox1.SelectedValue));
    }
}