C# 如何在Windows 8.1中访问HubSection内的控件
我使用的HubbSection如下所示:C# 如何在Windows 8.1中访问HubSection内的控件,c#,json,xaml,windows-store-apps,C#,Json,Xaml,Windows Store Apps,我使用的HubbSection如下所示: <HubSection Header="Section1"> <DataTemplate> <TextBox /> </DataTemplate> </HubSection> <HubSection Header="Section1"> <DataTemplate> <TextBox /> </DataTemplate&
<HubSection Header="Section1">
<DataTemplate>
<TextBox />
</DataTemplate>
</HubSection>
<HubSection Header="Section1">
<DataTemplate>
<TextBox />
</DataTemplate>
</HubSection>
<HubSection Header="Section1">
<DataTemplate>
<TextBox />
</DataTemplate>
</HubSection>
现在根据问题和文章,我可以很好地为文本框使用Loaded
事件,如下所示,并设置值
<TextBox Loaded="TextBox_Loaded" />
private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
var txtBox = (TextBox)sender;
txtBox.Text = "Some Text";
}
已加载私有无效文本框(对象发送方,路由目标)
{
var txtBox=(TextBox)发送方;
txtBox.Text=“一些文本”;
}
但问题是,如果我在每个HubSection
中都没有更多的控件可以绑定/访问,那么这样做是不好的
有人能告诉我是否有其他简单的方法来绑定控件。试试这个:
C#:
在代码隐藏类(例如页面
)中,您需要定义一个包含根对象
的属性。请注意,如果要对此属性值的更改做出反应,可能需要实现
public Page1 : Page {
public RootObject RootObject { get; set; }
}
XAML:
然后,在XAML中,您只需使用对RootObject
属性的绑定,如下所示:
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding RootObject.Text1}" />
</DataTemplate>
</HubSection>
<HubSection Header="Section2">
<DataTemplate>
<TextBox Text="{Binding RootObject.Text2}"/>
</DataTemplate>
</HubSection>
希望这有帮助
C#
}
XAML
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Hub >
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding Text1}"/>
</DataTemplate>
</HubSection>
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding Text2}"/>
</DataTemplate>
</HubSection>
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding Text3}"/>
</DataTemplate>
</HubSection>
</Hub>
</Grid>
输出
您可以在数据模板中使用,并将控件添加到堆栈面板中。这样,,您可以在每个HubSection中绑定或访问更多控件。@MattewU MSFT,但我仍然有三个HubSection
s,我想从一个对象绑定所有HubSection
中的所有控件,比如这里的RootObject
@DeepakSharma您想动态生成HubSections
它是一个定义的计数3?@rbr94它是一个定义的计数。我只想从上面定义的RootObject
类绑定HubSection
中的所有控件。@DeepakSharma,如果我理解正确的话。这意味着您要将第一个TextBox.Text
属性绑定到RootObject
的Text1
,第二个绑定到Text2
,依此类推?您想使用RootObject
填充文本框,还是用其他方法?
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
RootObject ro = new RootObject() {Text1 = "Header1JsonData",Text2= "Header2JsonData",Text3= "Header3JsonData"};
this.DataContext = ro;
}
}
public class RootObject
{
public string Text1 { get; set; }
public string Text2 { get; set; }
public string Text3 { get; set; }
}
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Hub >
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding Text1}"/>
</DataTemplate>
</HubSection>
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding Text2}"/>
</DataTemplate>
</HubSection>
<HubSection Header="Section1">
<DataTemplate>
<TextBox Text="{Binding Text3}"/>
</DataTemplate>
</HubSection>
</Hub>
</Grid>