簡體   English   中英

如何通過代碼設置ComboBox的SelectedItem

[英]How to set a ComboBox's SelectedItem through code

在用戶控件中,我定義了一個組合框,如下所示:

<GroupBox x:Name="stopEventGroup" Header="Test">
<ComboBox x:Name="stopEventCombobox" 
          ItemsSource="{Binding}" 
          DisplayMemberPath ="EventVariableComboxItem" 
          SelectedItem="StopEventVariable"/>
</GroupBox>

StopEventVariable是我的對象(日志)的屬性。 在代碼部分,我將其SelectionChanged事件綁定到處理程序方法:

stopEventCombobox.SelectionChanged += stopEventCombobox_SelectionChanged;

在處理程序內部,我將其分配給對象的屬性。

private void stopEventCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    selectedVar = (LogPublicVariableView)stopEventCombobox.SelectedItem;

    if ((log != null) && (selectedVar != null))
    {
        log.StopEventVariable = selectedVar.ExposedVariable;
    }
}

在此構造函數的構造函數中,我綁定了combobox父對象的數據上下文:

stopEventGroup.DataContext = pvVarList;

到現在為止,一切正常。 現在我的問題是。 我的對象(日志)存儲該值之后,下次,當我顯示此用戶控制器時,我希望combobox可以自動顯示此值,我嘗試在用戶控制器的構造函數中的以下代碼中進行操作,但無法正常工作:

stopEventCombobox.SelectedItem = log.StopEventVariable;

分配后,stopEventCombobox.SelectedItem仍為null。

您尚未將SelectedItem綁定到StopEventVariable 使用以下語法: SelectedItem="{Binding StopEventVariable}"

還要確保StopEventVariable是一個屬性。

從XAML本身將SelectedItem屬性與您的源屬性(StopEventVariable)綁定

<ComboBox x:Name="stopEventCombobox" 
          ItemsSource="{Binding}" 
          DisplayMemberPath ="EventVariableComboxItem" 
          SelectedItem="{Binding StopEventVariable}"/>

如果您的意思是從后面的代碼綁定,則必須執行以下操作:

Binding b1 = new Binding("StopEventVariable");
b1.Source = pvVarList;
stopEventCombobox.SetBinding(ComboBox.SelectedItemProperty, b1);

然后,您只需要設置屬性StopEventVariable。 例如:

pvVarList.StopEventVariable = someItemsCollection [0];

暫無
暫無

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

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