请参阅Windows 8.1项目中xaml.cs文件中的xaml元素

时间:2016-05-06 15:35:48

标签: c# xaml windows-8.1

您好我正在使用Visual Studio 2015学习Windows 8.1开发 如何从关联的.xaml.cs文件中引用.xaml文件中的xaml元素

MainPage.xaml文件:

<Page
x:Class="project.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:project"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

        <HubSection Width="600" x:Uid="Section1Header" Header="Map">
        <DataTemplate>
            <Grid>
                <Button x:Name="mapButton" Content="Find my location"/>
            </Grid>
        </DataTemplate>
    </HubSection>
//...

MainPage.xaml.cs文件:

namespace project
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            mapButton.Click += mapButton_Click;
        }
}

mapButton我收到错误:名称&#39; mapButton&#39;并不存在于实际情境中 我认为x:Name是一种给出名称的方法,我可以从.xaml.cs文件中访问xaml元素。

1 个答案:

答案 0 :(得分:1)

此处的问题是您尝试从生成的内容中访问按钮的名称。 mapButton不在Page的范围内,而是在HubSection的范围内。你真正需要做的是,如果你想访问button元素,就是使用VisualTreeHelper在运行时获取按钮。

这是一个例子。

辅助功能:

internal static void FindChildren<T>(List<T> results, DependencyObject startNode) where T : DependencyObject
{
    int count = VisualTreeHelper.GetChildrenCount(startNode);
    for (int i = 0; i < count; i++)
    {
        DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
        if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
        {
            T asType = (T)current;
            results.Add(asType);
        }
        FindChildren<T>(results, current);
    }
}

访问按钮:

public MainPage()
{
    this.InitializeComponent();
    Loaded += (sender, e) =>
    {
        List<Button> results = new List<Button>();
        FindChildren(results, Hub);
        var mapButton = results.Find(item => item.Name.Equals("mapButton"));
        mapButton.Click += mapButton_Click;
    };
}

private void mapButton_Click(object sender, RoutedEventArgs arg)
{
    // Do something...
}

虽然如果您真的想将命令映射到Click,您应该考虑通过binding在XAML中执行此操作。