c# - GridView、ItemTemplate、DataTemplate 绑定(bind)在 C# 代码后面

标签 c# windows xaml windows-runtime win-universal-app

我有以下可用的 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/

相关文章:

python - Enthought Canopy 中的 IPython 缓冲区和分页

c++ - "An existing connection was forcibly closed by the remote host"监听传入数据时

wpf - 正确使用 PropertyChangedTrigger 和 ChangePropertyAction

c# - 在运行时创建具有通用接口(interface)的通用类型

c# - 使用 WebClient DownloadStringAsync 下载时引发 TargetInvocableException

c# - 无法使用 API 更改 Power BI 连接字符串

python - python的命令行界面

c# - 使用 MVVM LIGHT (WPF) 在 UserControl 中导航

c# - WPF Path/"up"箭头被截断 2px

c# - 在资源文件中存储包含函数和超链接的大文本