[英]When ConvertBack is called for ItemsControl?
我有以下項目數據類,以及一個轉換器。
class ListBoxViewItem
{
public String Name { get; set; }
public Boolean IsChecked { get; set; }
}
[ValueConversion(typeof(List<String>),typeof(List<ListBoxViewItem>))]
class ListToItemConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
IEnumerable<String> l = value as IEnumerable<String>;
return (from n in l select new ListBoxViewItem() { IsChecked = true, Name = n });
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
class ListBoxData
{
public List<String> AllData
{
get
{
return new List<string>()
{
"FOO",
"BAR"
};
}
set
{
}
}
}
我將ListBoxData
的實例綁定到列表框控件的ItemsSource
。 如下:
<ListBox>
<ListBox.ItemsSource>
<Binding>
<Binding.Path>AllData</Binding.Path>
<Binding.Converter>
<local:ListToItemConverter />
</Binding.Converter>
<Binding.Mode>TwoWay</Binding.Mode>
</Binding>
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked,Mode=TwoWay}"
Content="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
所以我的問題是,顯示列表框時會調用Convert
函數,但是由於此列表框中的每個項目都是一個復選框,盡管我使用TwoWay
綁定來綁定實例和列表框,但是當我選中/取消選中時,不會調用ConvertBack
此列表框中的復選框。
我不確定ConvertBack
是否可以按預期工作。 但是,如果我希望在更改支票狀態時可以觸發ConvertBack
,該怎么辦?
當在Mode = TwoWay的綁定中使用Converter時,將觸發ConvertBack方法。 示例是用於綁定到TextBox的Text屬性的示例。 當在TextBox中顯示值時更改值時,將觸發“轉換”方法,而當用戶更改TextBox值時,將觸發“ ConvertBack”。
將UpdateSourceTrigger添加到Binding中,並使用Convert
函數的反向功能實現ConvertBack
函數。
更改以下
<CheckBox IsChecked="{Binding IsChecked,Mode=TwoWay}">
至
<CheckBox IsChecked="{Binding IsChecked,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
ConvertBack函數如下
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is IEnumerable<ListBoxViewItem>)
{
var l = (IEnumerable<ListBoxViewItem>)value;
return l.Select(l.IsChecked);
}
return null;
}
您正在轉換ListBox.ItemsSource
,而不是CheckBox.IsChecked
我不認為ListBox.ItemsSource
甚至不能與TwoWay
綁定一起使用,因為默認情況下,ListBoxes不會對其ItemsSource的源集合進行更改。
如果要在更改CheckBox.IsChecked
時使轉換器運行,則需要指定要在IsChecked
綁定中使用的轉換器
<CheckBox IsChecked="{Binding IsChecked,
Converter={StaticResource MyCheckboxConverter}}"
Content="{Binding Name}"/>
但是在這種情況下,由於IsChecked
已經是一個布爾值,因此不需要轉換器,因此根本不需要轉換它。
如果您試圖在CheckBox.IsChecked
更改時觸發某些內容,最好確保IsChecked
觸發PropertyChange
通知,並在包含IsChecked
屬性的類的PropertyChanged
事件中執行代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.