【问题标题】:Dynamically align width of WPF DataGrid columns动态对齐 WPF DataGrid 列的宽度
【发布时间】:2019-10-11 18:30:25
【问题描述】:

有一个 WPF DataGrid 具有在 Ctrl+MouseWheel 事件上动态更改 FontSize 的功能。
它是使用 Caliburn 的 cal:Message.Attach 功能实现的:

<!-- xaml -->
cal:Message.Attach="[Event PreviewMouseWheel] = [Action ChangeDataGridFont($eventArgs)]"

C# 视图模型:

public void ChangeDataGridFont(MouseWheelEventArgs args)
{
    if (Keyboard.Modifiers == ModifierKeys.Control && args != null)
    {
        DataGridFontSize += Math.Sign(args.Delta) * 2;
        args.Handled = true;
    }
}

DataGridFontSize 是绑定到CellStyleDataGrid 的VM 属性。

加载时列的宽度与内容对齐 - 好的:

如果用户增加字体大小,那么列宽会自动调整 - 好的:

但是,当字体大小减小时 - 不调整列。见空白:

有没有办法克服这种影响(如果可能,在 MvvM 的范围内)?

更新:看起来我们在更改FontSize 时需要手动更新列宽。我可以在相应的样式中绑定列的宽度:

<Style x:Key="IdCellStyle" TargetType="{x:Type DataGridCell}" >
    <Setter Property="Width" Value="{Binding DataContext.ColWidth, Mode=TwoWay, 
                                    RelativeSource={RelativeSource AncestorType=UserControl}}" />
    ....
</Style>

并定义属性:

public double ColWidth
{
    get => _colWidth;
    set
    {
        _colWidth = value;
        NotifyOfPropertyChange();
    }
}

我应该在DataGridFontSize setter 中将ColWidth 设置为什么?

【问题讨论】:

    标签: c# wpf mvvm datagrid


    【解决方案1】:

    我刚刚添加了Width,因为DataGridColumn 看起来很有效。试试看。

    <Window.Resources>
        <XmlDataProvider x:Key="MockList"   XPath="/MockObjects/*" >
            <x:XData >
                <MockObjects xmlns="">
                    <MockObject  Name="Louis" Type="TTTT" Number="1" />
                    <MockObject Name="Joseph" Type="TTTT" Number="2" />
                    <MockObject Name="Papineau" Type="ZZZZ" Number="3" />
                </MockObjects>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <Grid DataContext="{Binding Source={StaticResource MockList}}" >
        <DataGrid HorizontalAlignment="Stretch" Margin="10" VerticalAlignment="Stretch" 
                  ItemsSource="{Binding Mode=Default, XPath=/MockObjects/MockObject}" 
                  AutoGenerateColumns="False" PreviewMouseWheel="UIElement_OnPreviewMouseWheel">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding XPath=@Name}" Width="*"></DataGridTextColumn>
                <DataGridTextColumn Header="Type" Binding="{Binding XPath=@Type}" Width="*"></DataGridTextColumn>
                <DataGridTextColumn Header="Number" Binding="{Binding XPath=@Number}" Width="*"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    

    【讨论】:

    • 我看到的是,在您的示例中,所有列的宽度都是固定的。并且您没有在开始时根据内容调整列。另外:当您最终放大时,“Papineau”不适合该列。
    • @IgorStack 如前所述,您可以将宽度固定为您想要的任何大小。我只是把* 使DataGrid 将所有列扩展到最大。现在您知道何时更新字体大小,并在代码中更新宽度以使其正常工作。我的观点是当你滚动鼠标时你必须手动调整宽度。希望这会有所帮助
    猜你喜欢
    • 2015-03-20
    • 2012-06-06
    • 2011-01-28
    • 2013-07-26
    • 2014-06-06
    • 2011-08-22
    • 2017-10-19
    • 2011-10-09
    • 1970-01-01
    相关资源
    最近更新 更多