我有一個ComboBox
,它的Items
屬性綁定到一組對象。我還將SelectedItem
屬性綁定到整個集合,其中ValueConverter
設計用於檢查集合中的元素並返回要選擇的1個項目。這部分工作。讓'ConvertBack(...)'在WPF組合框選擇更改上觸發
不起作用的是當用戶在組合框上進行選擇更改時,ValueConverter
的ConvertBack(...)
方法未被調用。我需要調用ConvertBack(...)
,因爲我需要接受用戶的選擇,重新檢查集合,並適當地編輯舊選定項目和新選定項目。
我知道這種方法是一個尷尬,但它是這樣的。下面是相關的代碼:
組合框:
<ComboBox ItemsSource="{Binding}" SelectedItem="{Binding Path=., Converter={StaticResource ResourceKey=DataInputAssetChoiceSelectedItemConverter}}" />
ValueConverter:
public class DataInputAssetChoiceSelectedItemConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
foreach (CustomObject Choice in (Collection<CustomObject>)value)
{
if (Choice.IsSelected)
{
return Choice;
}
}
return ((Collection<CustomObject>)value).First();
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ //breakpoint...execution never gets here!
return null;
}
}
那麼,爲什麼不ConvertBack(...)
曾經被調用?這只是我誤解ComboBox
?我試過這種方法,使用SelectedItem
,SelectedValue
,SelectedIndex
,並試圖搞亂UpdateSourceTrigger
,各種綁定模式,DataTriggers,並且永遠不會得到ConvertBack(...)
被調用。正在使用SelectionChanged
事件的唯一選項?如果是這樣,爲什麼?
感謝您的這個珍聞。基於這種行爲,可能使用DataContext作爲綁定的源代碼應該被禁止,因爲它無法完全參與綁定。我想我必須使用SelectionChanged事件並從那裏編輯DataCollection的內容。要麼或更改數據模型,以便我可以綁定到一個實際的屬性......但這將是可怕的。 – tyriker 2011-05-11 18:24:59
標記爲答案,因爲你解釋了爲什麼ConvertBack(...)不適用於這種特殊情況。謝謝。 – tyriker 2011-05-11 19:24:47