2017-02-14 71 views
0

如何将我的ListBox中的CheckBox设置为禁用?如何将我的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的动态是我的列表框的里面。但是,当我禁用列表框时,它也禁用了我的垂直滚动条。所以现在我想我应该访问我的GroupBox里面的列表框内的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

尝试绑定IsEnabled属性。 – Dexion

回答

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)); 
    } 
} 

而且CheckBoxIsEnabled属性绑定到这个属性:

<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" IsEnabled="{Binding IsEnabled}" /> 

您可以简单地设置您的源集合中的MyItemsClassThing对象的IsEnabled属性,以停用Checkbox

foreach(var item in MyListBoxThing.Items.OfType<MyItemsClassThing>()) 
{ 
    item.IsEnabled = false; 
} 
+0

不幸的是,它编译但没有工作。 – Yusha

+0

您究竟如何设置MyItemsClassThing ItemsSource集合呢?这应该是一个IEnumerable 。那么它应该工作,只要你已经正确实施了INotifyPropertyChanged。请发布您的完整代码。 – mm8

+0

看来我在模仿你的代码时犯了一个人为错误。我得到它的工作。谢谢你的精彩解决方案!非常感谢我的朋友!这真的有帮助! – Yusha

相关问题