![](/img/trans.png)
[英]In WPF/C#, how do I access elements of dynamically generated controls or otherwise add click events to them?
[英]How do I dynamically add and position CheckBox elements in WPF?
我開始制作WinForms應用程序以顯示4×4×4復選框的網格,代表真實的4 3 LED網格。
這是現在的樣子:
我想將其轉換為WPF應用程序,以便可以使用WPF Checkbox的透明度選項,使未選擇的復選框[將有4層]圖層略微透明,以使其具有更真實的3D感覺。
我是WPF的新手,我嘗試在主窗口中嵌套2個元素(例如,2個網格以稍微重疊該位置,可能相距20個像素,以便它們看起來像是3d交錯的),但它只是贏了我不能那樣做,只能讓我在原始網格內添加一個子網格。
TLDR:如何在給它們提供絕對像素位置的同時動態創建許多復選框?
我當前使用的WinForms C#代碼:
int spacing = 25;
int zero = 0;
for (int z = 1; z <= 4; z++)
{
List<string> zString = new List<string>();
for (int y = 1; y <= 4; y++)
{
for (int x = 1; x <= 4; x++)
{
int pixel_x = zero + ((x - 1) * spacing);
int pixel_y = (zero - 4) + ((y - 1) * spacing);
//int id = ((y - 1) * 4) + x;
CheckBox box = new CheckBox();
box.CheckStateChanged += new System.EventHandler(checkBox2_CheckedChanged);
box.Tag = id;
zString.Add(id.ToString());
//box.Text = id.ToString();
box.BackColor = Color.Transparent;
//box.
box.AutoSize = false;
box.Size = new Size(20, 20);
box.Padding = new Padding(3);
box.Location = new Point(pixel_x, pixel_y);
this.Controls.Add(box);
id++;
}
}
zero += 25;
}
考慮使用ItemTemplate (或DataTemplate)來建立每個項目在viewmodel集合中的外觀。
例:
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我將使用多個UniformGrid
,它們在規則網格內彼此堆疊(因此它們重疊)。 每個UniformGrid的頂部和左側邊距將偏移特定的數量。
每個UniformGrid的項目源都將綁定到視圖模型上每個“層”的布爾屬性列表。
你可以試試看 在窗口內使用畫布。
<Window x:Name="myWindow1" x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Canvas x:Name="canvas" >
</Canvas>
與Windows窗體中可用的“位置”不同,您可以使用“邊距”來設置位置
int spacing = 100;
int zero = 0;
for (int z = 1; z <= 4; z++)
{
List<string> zString = new List<string>();
for (int y = 1; y <= 4; y++)
{
for (int x = 1; x <= 4; x++)
{
int pixel_x = zero + ((x - 1) * spacing);
int pixel_y = zero + ((y - 1) * spacing);
CheckBox box = new CheckBox();
Canvas.SetLeft(box, pixel_x);
Canvas.SetTop(box, pixel_y);
this.canvas.Children.Add(box);
}
}
zero = zero + 50;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.