我有一系列标有24小时制的按钮。例如;
<StackPanel Orientation="Horizontal">
<ToggleButton Content="00:00" Name="thetime0000"/>
<ToggleButton Content="01:00" Name="thetime0100" />
<ToggleButton Content="02:00" Name="thetime0200" />
<ToggleButton Content="03:00" Name="thetime0300" />
等
现在我将每个元素的值存储在数据库中作为BIT,我试图将它们关联起来,以便它们被选中或不被选中。我有一个想法,试图枚举所有的切换按钮,但不能到那么远;
System.Windows.Controls.Primitives.ToggleButton [24] fudge =
new System.Windows.Controls.Primitives.ToggleButton [24];
fudge[0] = thetime0000;
fudge[1] = thetime0100;
我可以通过元素名称或数字直接调用元素吗?有什么想法吗?
答案 0 :(得分:1)
您可以按名称访问控件:
thetime0000.IsChecked = true;
答案 1 :(得分:0)
创建以下内容:
水平ListView:
<ListView ItemsSource="{Binding myClocks}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<ToggleButton />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
包含两名成员Time
和IsChecked
的小组:
Class MyClock : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string time;
Nullable<bool> isChecked;
public string Time
{
get { return time };
set
{
time = value;
OnPropertyChanged("Time");
}
};
// Similarly create property for isChecked
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
有关implementing property change notification see here
的更多详情包含MyClock实例列表的ObservableCollection:
ObservableCollection<MyClock> myClocks = new ObservableCollection<MyClock>();
将24个项目添加到集合中:
for(int i=0; i<24; i++)
myClocks.Add(new MyClock{ Time = String.Format("00:{0}",i.ToString("D2"}), IsChecked = false });
你的ListView的ItemsSource已经设置为标记中的ObservableCollection(见上文)
希望您已经设置了DataContext。
现在每当用户点击ToggleButton时,True / False / Null值将传播到您的属性,反之亦然。