因此,我一直在尝试制作一个列表项,该列表项将在触发列表框时切换复选框。当不涉及绑定时,我已经能够成功地做到这一点,但是一旦我添加绑定,它就永远不会更新绑定,但仍然会更新复选框上的 ischecked。我希望它选中该框并更新我的 IsSelectedName 绑定,以便我知道用户选中了它。此外,如果我在复选框 IsSelectedName 上单击鼠标右键,则会更新。这是我的代码的最简单版本:
<ListBox Grid.Column="1" Margin="20" ItemsSource="{Binding listitems}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckboxIsSelected" IsChecked="{Binding IsSelectedName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}" Value="True">
<Setter TargetName="CheckboxIsSelected" Property="IsChecked" Value="True"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
提前致谢
这是视图模型:
public class ListTestVM
{
public List<listem> listitems { get; set; }
public ListTestVM()
{
listitems = new List<listem>()
{
new listem(){ Name = "Test", IsSelectedName = false },
new listem(){ Name = "Test1", IsSelectedName = true },
new listem(){ Name = "Test2", IsSelectedName = false },
new listem(){ Name = "Test3", IsSelectedName = true }
};
}
}
这是列表项类:
public class listem :INotifyPropertyChanged
{
private bool _IsSelectedName;
public bool IsSelectedName
{
get { return _IsSelectedName; }
set
{
_IsSelectedName = value;
NotifyPropertyChanged("IsSelectedName");
}
}
public string Name { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}