2014-08-29 62 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