過去に行ったことは、ListBox に表示するオブジェクトのラッパー クラスを作成することです。このクラスToString
では、ListBox に表示する文字列にオーバーライドします。
選択した項目の詳細を取得する必要がある場合は、それをラッパー クラスにキャストし、必要なデータを取得します。
これは醜い例です:
class FileListBoxItem
{
public string FileFullname { get; set; }
public override string ToString() {
return Path.GetFileName(FileFullname);
}
}
ListBox に FileListBoxItems を入力します。
listBox1.Items.Add(new FileListBoxItem { FileFullname = @"c:\TestFolder\file1.txt" })
次のように、選択したファイルの完全な名前を取得します。
var fileFullname = ((FileListBoxItem)listBox1.SelectedItem).FileFullname;
Edit
@ user1154664 は、元の質問に対するコメントで良い点を挙げています: 表示されたファイル名が同じ場合、ユーザーは 2 つの ListBox アイテムをどのように区別しますか?
次の 2 つのオプションがあります。
各 FileListBoxItem の親ディレクトリも表示する
これを行うには、ToString
オーバーライドを次のように変更します。
public override string ToString() {
var di = new DirectoryInfo(FileFullname);
return string.Format(@"...\{0}\{1}", di.Parent.Name, di.Name);
}
ツールチップに FileListBoxItem のフル パスを表示する
これを行うには、ToolTip コンポーネントをフォームにドロップMouseMove
し、ListBox のイベント ハンドラーを追加して、ユーザーがマウスを重ねているFileFullname
プロパティ値を取得します。FileLIstBoxItem
private void listBox1_MouseMove(object sender, MouseEventArgs e) {
string caption = "";
int index = listBox1.IndexFromPoint(e.Location);
if ((index >= 0) && (index < listBox1.Items.Count)) {
caption = ((FileListBoxItem)listBox1.Items[index]).FileFullname;
}
toolTip1.SetToolTip(listBox1, caption);
}
もちろん、この 2 番目のオプションを最初のオプションと共に使用することもできます。
ListBox 内の ToolTip のソース(受け入れられた回答、私が好むフレーバーに再フォーマットされたコード)。