我爲CodeProject上的文章寫了一個快速應用程序(完整文章here。您可以直接從here下載此問題的源代碼)。更改列表框SelectedValuePath引發異常
這是一個非常簡單的窗口,它具有帶簡單對象的ListBox(3個屬性:2個字符串,1個int)。
public class MyShape
{
public string ShapeType { get; set; }
public string ShapeColor { get; set; }
public int ShapeSides { get; set; }
}
我設置SelectedValuePath
在後面的代碼,以便用戶可以選擇從組合框的屬性,並查看當前的SelectedValue
的標籤。
組合框被設置爲類型的對象:
public class PropertyObject
{
public string PropertyName { get; set; }
public string PropertyType { get; set; }
}
這兩個屬性是字符串,所以,應該是作爲SelectedValuePath
輸入有效。
我設置值是這樣的:
private void ShapeClassPropertiesCmbx_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cmbx = (ComboBox)sender;
PropertyObject prop_ob = ((PropertyObject)cmbx.SelectedItem);
string name = prop_ob.PropertyName;
var item_index = SourceListBox.SelectedIndex;
//SourceListBox.SelectedValuePath = null; // without this, we get a null exceptions when going from string to int properties for some reason.
SourceListBox.SelectedValuePath = name;
SourceListBox.SelectedIndex = item_index;
}
(如果你下載的代碼,它是在MainWindow.xaml.cs線79)。
當我將所選值從string
更改爲int
時,會發生異常。 爲了避免混淆,兩者都會以string
表示要顯示的財產。
重現錯誤,註釋掉行79運行演示:
- 選擇任意的組合框SelectedValuePath(注:第二個)第2個屬性。
- 更改列表框中的選擇(您應該看到
SelectedValue
相應地發生變化) - 將第二個組合框中的選擇更改爲int屬性(實際上是一個字符串表示形式)。 拋出異常與錯誤:「輸入字符串的不正確的格式」
奇怪的是:如果你重複這些步驟,但首先選擇整型屬性,它工作正常。改爲一個字符串,然後,仍然正常工作。回到int,引發異常。
在設置之前將SelectedValuePath
設置爲null似乎可以解決問題。任何建議爲什麼你的例外被拋出,這有什麼問題?
編輯: 下面是一個新的演示,其中包含更多屬性類型。它還將顯示拋出什麼錯誤,並跟蹤SelectedIndex
:Download new demo。
如果我註釋掉第78行,'item_index'不再被定義。我是否應該評論第81行?啊,我明白了。你的意思是第79行。再試一次.... – ouflak
Argh,我的代碼似乎不同步。好吧,第79行。這是我在上面的課程中註釋掉的那個(它沒有在演示中註釋掉,因爲它會崩潰)。我也會更新這個問題。 – Noctis
當你把所有的事情都包下來的時候,看到你最後的項目會很有趣! – ouflak