在不更改/获取原始SelectedItem值的情况下更改ListBox中项目的外观

时间:2014-11-18 04:19:53

标签: c# wpf xaml listbox

我以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}"/>

然后我意识到我不想显示原始的foldernames(因为它们是隐藏的以$结尾的共享文件夹)。我想在ListBox上显示Title-cased并修剪最终的美元符号,所以我实现了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时,我得到原始(未转换)字符串的 clean 方式是什么?我可以直接访问属性,计算索引和比较,但可能有更简洁的方法。

1 个答案:

答案 0 :(得分:0)

有一种更简单的方法可以解决这个问题,而无需编写自定义转换器来剥离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));
    }
}