我在以下XAML代码中遇到了一些困难:
<ListBox x:Name="lstRegion" ItemsSource="{Binding}" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate DataType="ListBoxItem">
<CheckBox Content="{Binding Element.Region_Code}" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected, Mode=TwoWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这段代码将更新包含ListBoxItem的IsSelected属性,从而使我可以从lstRegion.SelectedItems返回此内容。
但是,当复选框的IsChecked值更改时,我还需要更新ItemsSource中的值。 有没有办法同时更新ItemsSource中的值和ListBoxItem?似乎我只能更改其中一个,而不能同时更改两个。 我确定我可以捕获PropertyChanged事件并手动更新值,但这似乎是因为我理解有误而做了额外的步骤。感谢任何帮助。
这是用于填充ListBox上的ItemsSource的类:
public class SelectionItem<T> : INotifyPropertyChanged
{
#region private fields
/// <summary>
/// indicates if the item is selected
/// </summary>
private bool _isSelected;
#endregion
public SelectionItem(T element, bool isSelected)
{
Element = element;
IsSelected = isSelected;
}
public SelectionItem(T element):this(element,false)
{
}
#region public properties
/// <summary>
/// this UI-aware indicates if the element is selected or not
/// </summary>
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected != value)
{
_isSelected = value;
PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
}
}
}
/// <summary>
/// the element itself
/// </summary>
public T Element { get; set; }
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
}