我有以下可用的 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>
背后的代码:
public MainPage()
{
this.InitializeComponent();
var _Colors = typeof(Colors)
.GetRuntimeProperties()
.Select(x => new
{
Color = (Color)x.GetValue(null),
Name = x.Name
});
this.DataContext = _Colors;
}
这很好用。
但我想在后面的 C# 代码中完成所有 XAML 部分。在 XAML 中,只有 MainGrid
会在那里,它的所有子元素和绑定(bind)都需要在代码隐藏中完成。
我在 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)
{
}
}
最佳答案
首先,我想建议您不要在代码中创建元素,除非您有充分的理由这样做。
无论如何,考虑到项目模板是类似工厂的控件对象(您为每个项目“生成”了一组新控件)。您使用 FrameworkElementFactory对子树建模,然后分配项目模板的 VisualTree属性(property)。
关于c# - GridView、ItemTemplate、DataTemplate 绑定(bind)在 C# 代码后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918489/