簡體   English   中英

設置列表框WPF的選定值

[英]Set the Selected value of listbox WPF

我最初將一些字符串對象添加到listBox ,然后再設置要選擇的Item:

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的第一項,而不是我嘗試設置的項...

為什么不使用綁定,像這樣。
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

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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM