使用以下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上ItemsItem的类:
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;
}
答案 0 :(得分:1)
类似的东西应该可以为您提供所需的东西:
<ListBox x:Name="lstRegion" ItemsSource="{Binding}" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate DataType="ListBoxItem">
<CheckBox Content="{Binding Element.Region_Code}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>