将Viewbox插入DataGrid单元格

时间:2012-02-27 11:44:26

标签: c# wpf

我想将一些内容放入ViewBox中,然后将此ViewBox添加到DataGridTemplateColumn的单元格模板中。所有这些都是在代码隐藏(C#)后完成的。

我使用Label完成了它,但我想使用ViewBox。使用Label的代码是:

 DataGridTemplateColumn dgtc5 = new DataGridTemplateColumn();

            dgtc5.Width = 142;
            dgtc5.Header = "Page Life Expectancy";
            DataTemplate dtemp5 = new DataTemplate();
            FrameworkElementFactory fef5 = new FrameworkElementFactory(typeof(Label));

Binding b5 = new Binding("PleChart");           
fef5.SetBinding(Label.ContentProperty, b5);

dtemp5.VisualTree = fef5;
dgtc5.CellTemplate = dtemp5;

1 个答案:

答案 0 :(得分:2)

请在此处查看我的回答Binding a DataGrid's CellTemplate content to an Element or a DependencyProperty defined on the templated CustomControl

只需像这样更改数据模板

<DataTemplate x:Key="template2">
    <Viewbox>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Funky: "/>
            <TextBlock Text="{Binding Path=Test, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomControl1}}}"/>
        </StackPanel>
    </Viewbox>
</DataTemplate>

导致包含的文本增大/缩小以适合视图框。

或者干脆就这样做:

<DataGrid.Columns>
    <DataGridTemplateColumn Header="Test">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Viewbox>
                    <TextBlock Text="{Binding Name}"/>
                </Viewbox>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>
相关问题