[英]GridView, ItemTemplate, DataTemplate binding in C# code behind
I have following working XAML and C# code behind: 我后面有以下工作XAML和C#代码:
<Grid x:Name="MainGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<GridView ItemsSource="{Binding}">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="100" Width="150">
<Grid.Background>
<SolidColorBrush Color="{Binding Color}"/>
</Grid.Background>
<StackPanel>
<StackPanel.Background>
<SolidColorBrush Color="{Binding Color}"/>
</StackPanel.Background>
<TextBlock FontSize="15" Margin="10" Text="{Binding Name}"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
CODE behind: 后面的代码:
public MainPage()
{
this.InitializeComponent();
var _Colors = typeof(Colors)
.GetRuntimeProperties()
.Select(x => new
{
Color = (Color)x.GetValue(null),
Name = x.Name
});
this.DataContext = _Colors;
}
This works fine. 这很好。
But I want to do all the XAML part in C# code behind. 但是我想在后面的C#代码中完成所有XAML部分。 In XAML, only
MainGrid
will be there, all its child elements and bindings needs to be done in code behind. 在XAML中,只有
MainGrid
在那里,其所有子元素和绑定都需要在后面的代码中完成。
I have tried something like this in MainPage_Loaded
event: 我已经在
MainPage_Loaded
事件中尝试过类似的操作:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
GridView gridView = new GridView()
{
ItemTemplate = new DataTemplate
{
//Don't know what to add here
}
};
Grid grid = new Grid();
Binding bindingObject = new Binding();
bindingObject.Source = this;
grid.SetBinding(Grid.BackgroundProperty, bindingObject);
//...
// Don't know how to add grid inside gridView in Code.
//...
MainGrid.Children.Add(gridView);
}
catch (Exception ex)
{
}
}
First of all I'd like to advise you not to create elements in code unless you have a real good reason to do so. 首先,我建议您不要在代码中创建元素,除非您有充分的理由这样做。
Regardless, considering that item templates are factory-like objects for controls (you 'spawn' a new set of controls for each item). 无论如何,考虑到项目模板是控件的工厂类对象(您为每个项目“生成”了一组新的控件)。 You use the FrameworkElementFactory to model the subtree and then assign that the item template's VisualTree property.
您可以使用FrameworkElementFactory建模子树,然后为其分配项目模板的VisualTree属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.