c# - 在itemscontrol wpf C#中命名后,如何检查使用itemscontrol动态创建的控件的状态
问题描述
对于我的代码,我使用绑定到类“MyClass”的 itemscontrol 创建了多个相同类型的控件(即 Checkbox)。我已将复选框控件命名为“checkControl”。现在,由于我在 UI 中创建了多个复选框控件,我想检查它们的状态并区分它们。我应该如何进行?我正在考虑使用 findvisualchild 和 findvisualparent?但是,我不知道如何使用它?
<ItemsControl Name="myList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="30,80,10,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Border x:Name="tempBorder" BorderBrush="LightGray" BorderThickness="2,2,2,2" CornerRadius="4,4,4,4" Margin="0,-30,-60,-30"
Background="LightGray">
<StackPanel Orientation="Horizontal" Background="Transparent" Margin="0">
<StackPanel Background="White" Orientation="Horizontal">
<CheckBox x:Name="checkControl" Margin="7,7,0,0" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked">
<WrapPanel>
<Image Source="/Images/myimage.png" Margin="0,10,0,0"></Image>
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBlock Text="{Binding Disk}" FontFamily="roboto" FontSize="14"/>
<Rectangle Width="340" Height="1" Margin="0,5,5,5" Fill="Black"/>
<TextBlock>
<Run Text="Item:" FontFamily="roboto" FontSize="14"/>
<Run Text="{Binding Path=Name, StringFormat=' {0} Jr.'}" FontSize="20" Foreground="Orange"
FontWeight="DemiBold"/>
</TextBlock>
</StackPanel>
</WrapPanel>
</CheckBox>
</StackPanel>
<StackPanel Orientation="Vertical" Background="LightGray" Margin="0" HorizontalAlignment="Center" Width="765"
VerticalAlignment="Center">
<TextBlock Text="Select the Option:" Margin="15,7,0,7" FontFamily="roboto"/>
<ComboBox x:Name="comboControl" Margin="15,5,0,7" Width="750" SelectionChanged="comboControl_SelectionChanged"/>
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
对于我的后端 C# 代码:类
public class MyClass
{
public string Disk { get; set; }
public string Name { get; set; }
public MyClass()
{
}
public MyClass(string album, string name)
{
this.Disk = album;
this.Name = name;
}
}
在我的 Xaml.cs
public ObservableCollection<MyClass> StudentDisk { get; set; }
//somecode
StudentDisk.Add(new MyClass("Disk 4 ", "John")); //For populating
//somecode
myList.ItemsSource = StudentDisk;
解决方案
可以通过它们的 DataContext 来区分复选框,这应该是唯一的:
void CheckBox_Checked(object sender, RoutedEventArgs e)
{
var checkbox = (CheckBox)sender;
var item = (MyClass)checkbox.DataContext;
MessageBox.Show(item.Disk + " " + item.Name);
}
推荐阅读
- python - 我可以发送 **kwargs 来代替 requests.post 中的 set 参数吗?
- xslt - 您可以在 XSL 中的分组分隔符上应用样式表吗?
- sql-server - 如何使用 System.Threading.Monitor 在 powershell 中锁定对象/类型?
- python - Pandas Dataframe 将多列分成箱并绘制每个
- vue.js - 在什么阶段使用 API(vuex)处理数据?
- html - 当屏幕放大或缩小时,如何使元素保持原位?
- python - Pyinstaller PermissionError: [Errno 13] Permission denied: run.exe
- powershell - 您如何使抽象的嵌套字典/哈希表对象可读(样式)?
- docker - 赛普拉斯没有连接到本地主机
- html - HTML:想要制作一个按钮列表并且文本不会改变颜色