c# - 绑定(bind) DataGridTemplateColumn

标签 c# wpf datagrid datatemplate datagridtemplatecolumn

似乎我在尝试在我的 DataGrid 上使用 DataTemplates 时遇到了困难。我想要做的是使用一个模板为每个单元格显示两行文本。但是似乎不可能以任何方式绑定(bind)列。

以下代码有望显示我希望做的事情。请注意每一列的绑定(bind):模板列没有这样的东西,因此,这个 xaml 不可能工作。

<Window.Resources>
    <DataTemplate x:Key="DoubleField">
        <StackPanel>
            <TextBlock Text="{Binding Value1}"/>
            <TextBlock Text="{Binding Value2}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Title}"/> // <- Binding does not exist for templatecolumn, I only wish it did
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Price}"/> // <- Binding does not exist for templatecolumn, I only wish it did
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Stuff}"/> // <- Binding does not exist for templatecolumn, I only wish it did
    </DataGrid.Columns>
</DataGrid>

class MyListItem {
    class DoubleItem {
        string Value1 { get; set; }
        string Value2 { get; set; }
    }    
    DoubleItem Title { get; set; }
    DoubleItem Price { get; set; }
    DoubleItem Stuff { get; set; }
}

我是否注定要将整个 DataTemplate 复制到每一列,只是为了对每个副本进行不同的绑定(bind)?当然有解决这个问题的好方法吗?或者我只是再次遗漏了一些非常明显的东西?

最佳答案

我不完全确定您要做什么,但如果您需要获取整行的 DataContext,您可以使用 RelativeSource 绑定(bind)在可视化树中向上移动。像这样:

<DataTemplate x:Key="DoubleField">
    <StackPanel>
        <TextBlock Text="{Binding DataContext.Value1, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
        <TextBlock Text="{Binding DataContext.Value2, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
    </StackPanel>
</DataTemplate>

关于c# - 绑定(bind) DataGridTemplateColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17470738/

相关文章:

c# - WPF ItemsSource 在代码隐藏中工作,但在 XAML 中不起作用

WPF : Binding cannot find source

c# - GridView 组合框数据绑定(bind) WPF

WPF 数据网格底部空行

C# ASP.NET DataGrid 复选框

c# - 为什么 MVC HttpPostedFileBase 总是空的?

c# - 构建 NuGet 包时如何向函数添加文档

c# - 何时在 Prism 中加载数据合适

c# - 设置 Focusable=False 导致 TabItem 在 wpf 中不可选

c# - 更新 DataGrid 的 ItemsSource 中的单个项目