2017-01-10 87 views
0

當我嘗試爲ComboBoxItem設置IsSelected時,它會拋出Set property 'IsSelected' threw an exception。我該怎麼辦?無法爲ComboBoxItem設置IsSelected屬性

這裏的XAML:

<ComboBox x:Name="rowsPerPageCombo" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" SelectionChanged="rowsPerPageCombo_SelectionChanged" Background="White"> 
     <ComboBoxItem x:Name="Page10" Content="10" IsSelected="True"/> 
     <ComboBoxItem x:Name="Page20" Content="20"/> 
     <ComboBoxItem x:Name="Page30" Content="30"/> 
     <ComboBoxItem x:Name="Page40" Content="40"/> 
     <ComboBoxItem x:Name="Page50" Content="50"/> 
</ComboBox> 
+1

您的XAML很好。你需要將你的代碼發佈到相關的組合框之後。以便我們能夠找到問題。你在你的rowsPerPageCombo_SelectionChanged中加入了斷點並且調試了 – Vijay

回答

1

嘗試SelectedIndex屬性設置爲0,而不是設置ComboBoxItem元素

<ComboBox x:Name="rowsPerPageCombo" SelectedIndex="0" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" SelectionChanged="rowsPerPageCombo_SelectionChanged" Background="White"> 
    <ComboBoxItem x:Name="Page10" Content="10" /> 
    <ComboBoxItem x:Name="Page20" Content="20"/> 
    <ComboBoxItem x:Name="Page30" Content="30"/> 
    <ComboBoxItem x:Name="Page40" Content="40"/> 
    <ComboBoxItem x:Name="Page50" Content="50"/> 
</ComboBox> 
+0

我也試過了。它拋出:System.Reflection.TargetInvocationException未處理 消息:在PresentationFramework.dll中發生未處理的類型爲'System.Reflection.TargetInvocationException'的異常 附加信息:異常已被調用目標拋出.' – Zolbayar

+0

你能發佈一些你使用這個ComboBox的C#代碼? – Peter

0

這很難說你的錯誤是沒有見過所選項目你的代碼,但確保窗口已經加載之前,在第一次嘗試任何事情在SelectionChanged事件處理程序。你可以立即返回,如果IsLoaded屬性返回false:

private void rowsPerPageCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (this.IsLoaded) 
     return; 

    //your code... 
} 

如果刪除SelectionChanged="rowsPerPageCombo_SelectionChanged"和不處理你可能會擺脫異常的SelectionChanged事件。否則,它與代碼中的其他內容有關。