c# - 在 C# 中构建数据模板

标签 c# wpf binding datatemplate frameworkelementfactory

我正在尝试在 C# 中构建以下 DataTemplate

<DataTemplate x:Key="lbl">
        <!-- Grid 2x2 with black border -->
        <Border BorderBrush="Black">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <!-- x-coordinate -->
                <TextBlock Text="X=" />
                <TextBlock Grid.Column="1" Text="{Binding Path=[XValues], Converter={x:Static my:Converters.Format}, ConverterParameter=#.##}"/>
                <!-- y-coordinate -->
                <TextBlock Grid.Row="1" Text="Y=" />
                <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Value, Converter={x:Static my:Converters.Format}, ConverterParameter=#.##}" />
            </Grid>
        </Border>
    </DataTemplate>

我已经走到这一步了,我无法弄清楚 Grid.ColumnDefinitions,我得到了一个异常(exception)

FrameworkElementFactory must be in a sealed template for this operation.

private static DataTemplate GetToolTipsDataTemplate()
{
        FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));

        FrameworkElementFactory x = new FrameworkElementFactory(typeof(TextBlock)); 
        x.SetBinding(TextBlock.TextProperty, new Binding("X="));
        grid.AppendChild(x);

        FrameworkElementFactory xValue = new FrameworkElementFactory(typeof(TextBlock));
        xValue.SetValue(TextBlock.TextProperty, "{Binding Path=[XValues], Converter={x:Static my:Converters.Format}, ConverterParameter=#.##}");
        grid.AppendChild(xValue);

        FrameworkElementFactory y = new FrameworkElementFactory(typeof(TextBlock));
        y.SetBinding(TextBlock.TextProperty, new Binding("Y="));
        grid.AppendChild(y);

        FrameworkElementFactory yValue = new FrameworkElementFactory(typeof(TextBlock));
        yValue.SetValue(TextBlock.TextProperty, "{Binding Path=Values, Converter={x:Static my:Converters.Format}, ConverterParameter=#.##}");
        grid.AppendChild(yValue);

        FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
        border.SetValue(Border.BorderBrushProperty, System.Windows.Media.Brushes.Black);
        border.AppendChild(grid);  

        DataTemplate dt = new DataTemplate {VisualTree = border};
        return dt;
    }

如有任何帮助,我们将不胜感激。

最佳答案

关于c# - 在 C# 中构建数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3773154/

相关文章:

c# - C# 和类中的嵌套枚举

wpf - 为什么这个 View 没有正确绑定(bind)到这个 ViewModel?

wpf - 虚拟化 ItemsControl?

events - 解除事件与 Dojo 的绑定(bind)

c# - 日期时间转换在不同计算机上失败/成功

c# - C#中存储过程的返回值返回错误

c# - 如何预加载 WPF 运行时引擎或如何减少其加载时间?

绑定(bind)和pmap交互变化?

c++ - 使用从字符串中提取的参数调用函数

c# - 从 Sharepoint 获取文件列表并下载最新文件