2017-02-14 30 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

相關問題