【问题标题】:First underscore in a DataGridColumnHeader gets removedDataGridColumnHeader 中的第一个下划线被删除
【发布时间】:2021-02-07 18:36:17
【问题描述】:

我遇到了一个问题,我有一个 DataGridColumnHeader,它接收带有下划线的文本作为内容,并且第一个下划线被隐藏,除非您按 alt(“data_grid_thing”显示为“datagrid_thing”)。我四处搜索位,并为标签找到了解决此问题的一些方法,因为如果将 RecognizesAccessKey 设置为 false,则文本将不会被视为“AccessText”(。但这不适用于 DataGridColumnHeader,因为它会删除所有其他样式,因此,我没有在其中包含文本的标题,而是得到带有文本的空格。我尝试使用 BasedOn 属性也没有效果。

我对通过 C# 端(可能通过某种方式找到 ContentPresenter 来修改 RecognizesAccessKey 属性)或通过修改 XAML(找出保留默认样式的方法)的解决方案持开放态度。

我的 XAML 看起来像这样:

  <Style x:Key="DataGridColumnHeaderStyle" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="DataGridColumnHeader">
                    <Border>
                        <ContentPresenter 
                            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                            RecognizesAccessKey="False" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>   
    </Style>

谢谢!

【问题讨论】:

标签: c# wpf xaml user-interface


【解决方案1】:

这是因为 AccessKey 处理。只需编写一个这样的事件处理程序来临时转义数据网格标题中的下划线。

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    string header = e.Column.Header.ToString();

    // Replace all underscores with two underscores, to prevent AccessKey handling
    e.Column.Header = header.Replace("_", "__");
}

【讨论】:

    【解决方案2】:

    blog post 表示您可以通过将下划线翻倍来转义:"data__grid_thing"

    另一种方法可以在this question接受的答案中找到

    【讨论】:

    • 遗憾的是,不能修改字符串。
    • @Stuart 按照链接中的建议在 TextBlock 中显示字符串怎么样?
    • 是的,成功了!谢谢!由于其他一些代码,这有点不雅,但并不可怕。
    【解决方案3】:

    我喜欢 umbreon222 的解决方案。如果你像我一样一直使用 DataGrids 并且有一个你总是引用的库(就像我一样),你可以创建一个 DataGrid 类的子类来一直注册该事件处理程序:

    using System.Windows.Controls;
    
    namespace MCLBZ7.Controls
    {
        public class MCLDataGrid : DataGrid
        {
            public MCLDataGrid() : base()
            {
                this.AutoGeneratingColumn += DG_AG_Header;
            }
    
            private void DG_AG_Header(object sender, DataGridAutoGeneratingColumnEventArgs e)
            {
                string header = e.Column.Header.ToString();
                e.Column.Header = header.Replace("_", "__");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2016-08-26
      • 1970-01-01
      • 2019-12-22
      • 2019-11-25
      • 2011-04-26
      相关资源
      最近更新 更多