设置列表框WPF的Selected值

时间:2014-08-29 10:32:56

标签: c# wpf listbox

我最初在listBox中添加了一些字符串对象,然后我想设置所选的项目:

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的第一项,而不是我尝试设置的项目......

2 个答案:

答案 0 :(得分: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;

不要忘记设置列表框的DataSource并实现INotifyPropertChanged

答案 1 :(得分: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;
    }
相关问题