[英]get all check boxes in a UserControl - WP8
我在UserControl的XAML中的网格布局中声明了复选框。
<CheckBox Content="Boo" Grid.Column="0" Grid.Row="0"/>
<CheckBox Content="Hoo" Grid.Column="0" Grid.Row="1"/>
我想以某种方式遍历C#中的所有这些复选框。 我该怎么做?
谢谢,
不需要以编程方式访问它们。 您应该使用ViewModel并将属性绑定到复选框。
public class SomeViewModel : INotifyPropertyChanged
{
private bool isCheckBoxOneChecked;
public bool IsCheckBoxOneChecked
{
get { return isCheckBoxOneChecked; }
set
{
if (value.Equals(isCheckBoxOneChecked))
{
return;
}
isCheckBoxOneChecked = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<CheckBox IsChecked="{Binding IsCheckBoxOneChecked}" Content="Boo" Grid.Column="0" Grid.Row="0"/>
<CheckBox Content="Hoo" Grid.Column="0" Grid.Row="1"/>
您还必须像这样设置DataContext
:
this.DataContext = new SomeViewModel();
通过xaml也可以做到这一点。
然后,您只需将IsCheckBoxOneChecked
属性设置为true即可自动选中该复选框。 如果用户取消选中该复选框,则该属性还将设置为false,反之亦然。
在这里看看: Model-View-ViewModel(MVVM)解释了
不过,如果您设置Grid
的Name
属性,则可以遍历所有子项:
// Grid is named 'MyGrid'
foreach (var child in this.MyGrid.Children)
{
if (child is CheckBox)
{
var checkBox = child as CheckBox;
// Do awesome stuff with the checkbox
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.