【问题标题】:Is it possible to edit only one control in DataGridTemplateColumn?是否可以在 DataGridTemplateColumn 中只编辑一个控件?
【发布时间】:2016-10-14 16:39:39
【问题描述】:

我做了一些研究,但没有找到我的问题的答案。就是这样:我有一个 DataGridTemplateColumn,里面有一个 StackPanel 和两个 TextBlocks。我希望能够只编辑其中一个 TextBlock,可以吗?

这是我的代码:

    <DataGrid Name="gdProducts"
              MinHeight="100" 
              ItemsSource="{Binding ProductsView, UpdateSourceTrigger=PropertyChanged}"
              SelectedItem="{Binding SelectedProduct, UpdateSourceTrigger=PropertyChanged}"
              AutoGenerateColumns="False"
              GridLinesVisibility="None"
              IsSynchronizedWithCurrentItem="False"
              CanUserAddRows="False"
              CanUserDeleteRows="False">
        <DataGrid.Columns>

            <!-- other columns -->

            <DataGridTemplateColumn Header="Waiting Period"
                                IsReadOnly="False"
                                Width="80">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding WaitingPeriod}"/>
                            <TextBlock Text=" days"/>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>
    </DataGrid>

代码的编写方式我将编辑两个 TextBlock(整个 StackPanel)。这不是我想要的。

谢谢!

编辑

抱歉我的错误,实际上我上面的代码根本不允许我编辑任何东西。我认为 IsReadOnly 设置为 False 将允许它像其他 DataGrid Column 类型一样可编辑。

【问题讨论】:

    标签: c# wpf datagrid datagridtemplatecolumn


    【解决方案1】:

    只需对要编辑的属性使用 TextBox 而不是 TextBlock:

      <StackPanel Orientation="Horizontal">
             <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.WaitingPeriod}"/>
             <TextBlock Text=" days"/>
       </StackPanel>
    

    RelativeSource 将您带到 DataGrid 的可视化树,DataGrid DataContext 是您的 ViewModel,这就是您有权访问 WaitingPeriod 属性的原因。

    【讨论】:

    • 感谢 Rom,这行得通。除了您的回答之外,我建议将 BorderThickness="0" 属性添加到 TextBox 以匹配 TextBlock 模板。
    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    相关资源
    最近更新 更多