【问题标题】:GridView, ItemTemplate, DataTemplate binding in C# code behindGridView、ItemTemplate、DataTemplate 绑定在 C# 代码后面
【发布时间】:2017-06-14 13:58:22
【问题描述】:

我有以下工作 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 会在那里,它的所有子元素和绑定都需要在代码中完成。

我在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)
    {

    }
}

【问题讨论】:

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


    【解决方案1】:

    首先,我想建议您不要在代码中创建元素,除非您有充分的理由这样做。

    无论如何,考虑到项目模板是类似工厂的控件对象(您为每个项目“生成”一组新控件)。您使用FrameworkElementFactory 对子树建模,然后为其分配项目模板的VisualTree 属性。

    【讨论】:

    • 对不起,但是 FrameworkElementFactory,VisualTree 对我来说似乎很混乱。
    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多