所以我一直在尝试创建一个列表项,在列表框被触发时将切换一个复选框。我没有涉及绑定时能够成功地执行此操作,但是一旦我添加了绑定,它就永远不会更新绑定,但仍会更新复选框上的缺陷。我希望它检查框并更新我的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));
}
}
}
答案 0 :(得分:1)
对于listItem属性使用ObservableCollection类型如下:
public ObservableCollection<listem> listitems { get; set; }
并在ListBox DataTemplate中将绑定模式设置为TwoWayeMode,如下所示:
<CheckBox Name="CheckboxIsSelected" IsChecked="{Binding IsSelectedName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
并删除你的触发器
答案 1 :(得分:0)
您是否在基类上使用了INotifyPropertyChanged接口? 触发PropertyChanged是有效的吗? 我认为这将是你问题的关键。