如何将我的ListBox中的CheckBox设置为禁用?
XAML:
<GroupBox Header="A GroupBox" BorderThickness="2" Width="247" HorizontalAlignment="Left" VerticalAlignment="Top" Height="183" Margin="405,155,0,0">
<Grid>
<ListBox Name="MyListBoxThing" ItemsSource="{Binding MyItemsClassThing}" Height="151" Width="215" HorizontalAlignment="Left" VerticalAlignment="Top" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Auto" Margin="10,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</GroupBox>
Mainwindow.xaml.cs
public class MyItemsClassThing
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
问题:我正在尝试禁用列表框内的CheckBox的动态。但是当我禁用ListBox时,它也会禁用我的垂直滚动条。所以现在我想我应该访问GroupBox里面的Listbox里面的CheckBox,然后逐个禁用它们。我怎么能这样做?
我试过了,但没有运气:
var children = LogicalTreeHelper.GetChildren(MyListBoxThing);
foreach(var item in children)
{
var c = item as CheckBox;
c.IsEnabled = false;
}
我想说:
loop through the listbox
if you find a check box
checkbox.isenabled = false
endif
end
提前致谢
答案 0 :(得分:2)
您应该向IsEnabled
添加MyItemsClassThing
属性并实施INotifyPropertyChanged
界面:
public class MyItemsClassThing : INotifyPropertyChanged
{
public string Name { get; set; }
public bool IsSelected { get; set; }
private bool _isEnabled = true;
public bool IsEnabled
{
get { return _isEnabled; }
set { _isEnabled = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
并将IsEnabled
的{{1}}属性绑定到此属性:
CheckBox
您只需设置源集合中<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" IsEnabled="{Binding IsEnabled}" />
个对象的IsEnabled
属性即可禁用MyItemsClassThing
:
Checkbox