【问题标题】:Create DataGridTemplateColumn with Image and Text WPF使用图像和文本 WPF 创建 DataGridTemplateColumn
【发布时间】:2017-01-04 14:16:45
【问题描述】:

我正在使用此代码创建一个显示图像和文本的列,但只显示文本,我做错了什么?

DataGridTemplateColumn col1 = new DataGridTemplateColumn(); col1.Header = "我的标题";

            FrameworkElementFactory factoryStackPanel = new FrameworkElementFactory(typeof(System.Windows.Controls.StackPanel));
            factoryStackPanel.SetValue(System.Windows.Controls.StackPanel.OrientationProperty, Orientation.Vertical);

            FrameworkElementFactory factoryTextBlock = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock));
            Binding bindTextBlock = new Binding("[" + i + "]");
            factoryTextBlock.SetValue(System.Windows.Controls.TextBlock.TextProperty, bindTextBlock);
            factoryTextBlock.SetValue(System.Windows.Controls.TextBlock.TextWrappingProperty, TextWrapping.Wrap);
            factoryTextBlock.SetValue(System.Windows.Controls.TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);

            FrameworkElementFactory factoryImage = new FrameworkElementFactory(typeof(System.Windows.Controls.Image));
            Binding bindImage = new Binding("http://www.pgn.co.id/images/modules/logo_pgn.png");
            factoryImage.SetValue(System.Windows.Controls.Image.SourceProperty, bindImage);

            factoryStackPanel.AppendChild(factoryImage);
            factoryStackPanel.AppendChild(factoryTextBlock);

            DataTemplate cellTemplate = new DataTemplate() { VisualTree = factoryStackPanel };

            col1.CellTemplate = cellTemplate;

            gridViewItens.Columns.Add(col1);

【问题讨论】:

  • 在 XAML 中做这些事情要容易得多。

标签: wpf image text datagridtemplatecolumn


【解决方案1】:

就像 Ed Plunkett 所说,在 XAML 中执行此操作要干净得多。假设您的DataGrid 绑定到某些项目的ObservableCollection,并且您的项目类具有MyTextMyImage 之类的属性,您可以执行以下操作:

<DataGridTemplateColumn Header="My Item">
     <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
          <StackPanel Orientation="Horizontal">
              <Image Source="{Binding MyImage}" />
              <TextBlock Text="{Binding MyText}" />
          </StackPanel>
      </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

【讨论】:

    【解决方案2】:

    DataGridTemplateColumn 使用数据模板,其工作方式与数据模板相同 您之前使用列表控件探索过的功能。 DataGridTemplateColumn 的唯一区别是 它允许您定义两个模板:一个用于数据显示(CellTemplate)和一个用于数据编辑(CellEditingTemplate),稍后您会考虑。这是一个使用模板数据列的示例 在网格中放置每个产品的缩略图:

    <DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
    <Image Stretch="None" Source=
    "{Binding Path=ProductImagePath, Converter={StaticResource ImagePathConverter}}">
    </Image>
    </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      相关资源
      最近更新 更多