在XAML中声明的Button不能在Class中引用

问题描述 投票:0回答:2

我有一个button我在Stack Panel中声明,如下所述。我想访问我班上的按钮,所以我可以改变myButton.Visibility = Visibility.Hidden的可见性,但它只是说myButton不存在。这似乎是XAML stack panel私人,我不知道为什么。

XAML

    <ItemsControl x:Name="ic">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding}" Foreground="White" TextWrapping="Wrap" FontSize="12" Margin="0, 0, 0, 0" Width="100" VerticalAlignment="Center" Padding="0"/>
                    <Button x:Name="myButton" Content="X" Foreground="Red" Width="15" Height="15" Background="Transparent" VerticalAlignment="Top" BorderThickness="0" Padding="0" Click="Remove_Click"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Class

myButton.Visibility = Visibility.Hidden; //myButton doesn't exist in current context
c# wpf xaml
2个回答
0
投票

由于您的按钮是在DataTemplate中声明的,因此您无法直接访问它,就像在其外部声明的对象一样。 (DataTemplate在添加到ItemsControl时提供模板对象的信息)

如果您希望只有一个,您可以删除它周围的整个对象,并以这种方式访问​​您的Button。

如果你计划在你的数组中有一个s,那么你将不得不考虑制作一个像这个网站上的搜索逻辑:https://dzone.com/articles/how-access-named-control


0
投票

此通用扩展方法将递归搜索所需类型的子元素:

public static T GetChildOfType<T>(this DependencyObject depObj) 
where T : DependencyObject
{
    if (depObj == null) 
        return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null) return result;
    }
    return null;
}

所以使用它你可以使用像这样的ic.GetChildOfType<Button>();

© www.soinside.com 2019 - 2024. All rights reserved.