2011-10-25 12 views
2

これには単純な解決策があると確信していますが、現時点ではそれを見つけることができません。LIstbox選択したアイテムの内容をテキストブロック

私は以下のコードを使用して、テキストとして選択リストボックスの内容をテキストブロック内に読み飛ばそうとしています。テキストブロックがちょうど

を表示するいくつかの理由

private void SelectionToText(object sender, EventArgs e) 
{ 
    ListBoxItem selection = (ListBoxItem)TextListBox.SelectedItem; 

    selectionText.Text = "This is the " + selection; 

} 

私はに変換されていないので、それは思った初期

「これはSystem.Windows.Controls.ListBoxItemです」文字列ですが、それもうまくいきませんでした。

提案がありますか?

+0

最初はListBoxItemにキャストしないでください。 ListBoxのコンテンツの種類は何ですか? –

+0

@EugeneCheverdaリストボックスの内容は文字列です。たとえば "item1" – Rhys

答えて

3

あなたは

public class MyListBoxItem 
{ 
    public MyListBoxItem(string value, string text) 
    { 
     Value = value; 
     Text = text; 
    } 

    public string Value { get; set; } 
    public string Text { get; set; } 

    public override string ToString() 
    { 
     return Text; 
    } 
} 

カスタムクラスを作成することができますListBoxItem

selectionText.Text= "This is the " + selection.Content.ToString(); 
+0

ありがとう、私はそれを逃したとは思えません。私は寝る必要があると思う。それはうまくいった。乾杯。 – Rhys

0

のContentプロパティを参照することができ、あなたのListBoxに項目を追加よう:

listBox1.Items.Add(new MyListBoxItem("1", "Text")); 

そして、この意志仕事

private void SelectionToText(object sender, EventArgs e) 
{ 
    MyListBoxItem selection = (MyListBoxItem)TextListBox.SelectedItem; 

    selectionText.Text = "This is the " + selection; 

} 
0

私は間違っていないよ場合は、次のコード

Convert.ToString(TextListBox.SelectedItem); 

を行う必要があります。これは、のSelectedItem

0

の値を返します。このよう入力してください:

private void SelectionToText(object sender, EventArgs e) 
{ 
    MyListBoxItem selection = (MyListBoxItem)TextListBox.SelectedItem; 

    selectionText.Text = "This is the " + selection.Content.ToString(); 

} 
1
string selText = selection.Items[selection.SelectedIndex].Text; 
0

または、Silverlightで、テキストブロックのテキストプロパティをバインドして、コードなしで行うことができます。 oリストボックスのselecteditem.contentプロパティ。

<TextBlock Text="{Binding SelectedItem.Content, ElementName=list}"/> 

ここで、listは私のListBoxの名前です。

関連する問題