簡體   English   中英

使用字符串或數組從C#訪問XAML元素

[英]Accessing XAML elements from C# using string or arrays

我是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;
            }
        }

使用FindName()方法。

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

    var ellipse = FindName(name_i) as Ellipse;

    if (ellipse != null)
    {
        ellipse.Width = width / 2;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM