2014-08-29 82 views
0

選定值我最初在listBox添加一些字符串對象,事後我想設置所選的項目:設置列表框的WPF

List <string> CustName = new List<string>(); 

....///add items to CustName///...  

listBox1.ItemsSource = CustName; 
string selection = "myselection" ///this string is contained in CustName  
listBox1.SelectedValue = selection; 

但是塔上面不起作用作用似乎是選擇的項目是該listBox而不是一個我嘗試設置的第一項...

+0

您是否嘗試過'listBox1.SelectedIndex = indexOfMySelection'? – 2014-08-29 10:41:01

回答

0

XAML:

<Grid> 
     <ListBox HorizontalAlignment="Left" Name="listBox1" Height="100" Margin="310,172,0,0" VerticalAlignment="Top" Width="100"/> 
    </Grid> 

CodeBehind.cs

public MainWindow() 
    { 
     InitializeComponent(); 
     List<string> CustName = new List<string>(); 
     CustName.Add("test1"); 
     CustName.Add("test2"); 
     CustName.Add("myselection"); 


     listBox1.ItemsSource = CustName; 
     string selection = "myselection"; 
     listBox1.SelectedItem = selection; 
    } 
+0

這是我固定的錯字...我也試過SelectedItem,但沒有結果 – apomene 2014-08-29 10:40:29

+0

@apomene檢查修改後的答案 – Sajeetharan 2014-08-29 10:44:41

1

爲什麼不使用綁定,這樣的事情。
XAML:

<ListBox ItemsSource={Binding CustName} SelectedItem={Binding MySelectedItem} /> 

然後有一個屬性

private string mySelectedItem; 
public string MySelectedItem 
{ 
get{return mySelectedItem;} 
set 
{ 
mySelectedItem=value; 
RaisePropertyChanged("MySelectedItem"); 
} 

,如果你想在代碼中手動設置的SelectedItem,然後就去做MySelectedItem = yourItem;

不要忘記設置數據源列表框,並實現INotifyPropertChanged