Skip to main content
 首页 » 编程设计

c#之使用字符串或数组从 C# 访问 XAML 元素

2024年02月05日21freeliver54

我是 WindowsApp 开发的新手,我试图通过使用数组的 C# 代码访问 XAML 元素。 例如,我的 XAML 代码中有几个省略号-

<Ellipse Fill="#FFF4F4F5" x:Name="E_0" Grid.Row="0" Grid.Column="2" Stroke="Black" RenderTransformOrigin="0.474,5.849"  Visibility="Visible" HorizontalAlignment="Center" VerticalAlignment="Center" /> 
<Ellipse Fill="#FFF4F4F5" x:Name="E_1" Grid.Row="0" Grid.Column="3" Stroke="Black" RenderTransformOrigin="0.474,5.849"  Visibility="Visible" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
<Ellipse Fill="#FFF4F4F5" x:Name="E_2" Grid.Row="0" Grid.Column="4" Stroke="Black" RenderTransformOrigin="0.474,5.849"  Visibility="Visible" HorizontalAlignment="Center" VerticalAlignment="Center"/> 

现在我想在 C# 中循环使用它们,所以我正在做类似于以下的事情-

string s1="E_"; 
double width=500; 
for (int i = 0; i < 2;i++ ) 
 { 
    string name_i = s1 + i.ToString(); 
    name_i.Width = width / 2; 
 } 

但是 name_i.width 给我一个错误。那么,我是否必须使用实际名称,我不能使用数组或字符串吗?使用实际名称会破坏目的,因为我有大约 50 个这样的元素需要处理。

请您参考如下方法:

正如 Maximillian 所建议的,您可以使用父容器并迭代其子容器:

Xaml:

 <StackPanel Name="StackPanelContainer"> 
      <Grid></Grid> 
      <Ellipse Name="E_0"></Ellipse> 
      <Ellipse Name="E_1"></Ellipse> 
      <Ellipse Name="E_2"></Ellipse> 
    </StackPanel> 

代码隐藏:

        //if you are sure every child element is a ellipse, you can use: 
        foreach (Ellipse child in StackPanelContainer.Children) 
        { 
            child.Width = 100; 
        } 
 
        //if there are also other elements, and also check if name starts with "E_" 
        foreach (object child in StackPanelContainer.Children) 
        { 
            var ellipse = child as Ellipse; 
            if (ellipse != null && ellipse.Name.StartsWith("E_")) 
            { 
                ellipse.Width = 100; 
            } 
        }