2013-03-27 47 views
1

在我的用戶控制設置組合框的的SelectedItem,我如下定義的組合框:如何通過代碼

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

在此構造函數的構造函數中,我綁定組合框的父級的數據上下文:

stopEventGroup.DataContext = pvVarList; 

到現在爲止,一切都可以正常工作。現在我的問題是。在我的對象(日誌)存儲值後,下次顯示此用戶控制器時,我希望組合框自動顯示此值,我嘗試在用戶控制器的構造函數中的以下代碼中執行此操作,但無法工作:

stopEventCombobox.SelectedItem = log.StopEventVariable; 

分配後,stopEventCombobox.SelectedItem仍爲空。

回答

0

您還沒有綁定SelectedItemStopEventVariable。使用以下語法:SelectedItem="{Binding StopEventVariable}"

另外確保StopEventVariable是一個屬性。

+0

是的,StopEventVariable是一個屬性。我在代碼部分綁定了DAtaContext。 – user2165899 2013-03-27 07:46:34

+0

@ user2165899顯示更多XAML。什麼是你的窗口的DataContext? – 2013-03-27 07:55:51

0

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

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

謝謝,我將它綁定在xaml部分,但仍然無法工作。 – user2165899 2013-03-27 07:51:07

0

如果你的意思是從代碼綁定後面,這裏是你必須做的:

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

然後你只需要設置屬性StopEventVariable。例如: :

pvVarList.StopEventVariable = someItemsCollection [0];