首页 > 解决方案 > DataGrid Column Width 字符串到宽度转换器 MVVM

问题描述

Right now I have a combobox with multiple different entries and when selected I want a datagrid I have to change column width according to the selected text from the combobox. 到目前为止,我已经尝试在我的窗口资源下的样式中使用转换器,但是,我的列的宽度不会根据输入的文本而改变,而是设置回自动。这是我的转换器:

public class BindingWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var Notation = value as string;
        if (Notation == null) return 26;
        switch (Notation)
        {
            case "size 1":
                return 26;
            case "size 2":
                return 40;
            case "size 3":
                return 45;
            case "size 4":
                return 50;
            case "size 5":
                return 60;
            default:
                return 26;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

这是它在我的 XAML window.resource 下的定义方式:

<Style x:Key="ElementStyle" TargetType="TextBlock">
        <Setter Property="TextAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="Width" Value="{Binding NotationType, UpdateSourceTrigger=PropertyChanged, IsAsync=True, Mode=TwoWay, Converter={StaticResource WidthConv}, ConverterParameter=0}"/>
</Style>

然后将其输入到我的 DataGrid.Column 部分:

<DataGridTextColumn Header="0" Binding="{Binding DataSpace, UpdateSourceTrigger=PropertyChanged, IsAsync=True, Converter={StaticResource DataConv}, ConverterParameter=0}"
    ElementStyle="{StaticResource ElementStyle}" 
    CellStyle="{StaticResource CellStyle0}" 
    HeaderStyle="{StaticResource HeaderStyle}"/>

有人能帮忙吗?

标签: c#wpfmvvmdatagridconverters

解决方案


您是否尝试过在 DataGrid 宽度本身而不是 TextBlock 中使用宽度转换器?

<DataGridTextColumn Header="0" 
     Binding="{Binding DataSpace, UpdateSourceTrigger=PropertyChanged, IsAsync=True, Converter={StaticResource DataConv}, ConverterParameter=0}"
     ElementStyle="{StaticResource ElementStyle}"
     Width="{Binding NotationType, UpdateSourceTrigger=PropertyChanged, IsAsync=True, Mode=TwoWay, Converter={StaticResource WidthConv}}"
     CellStyle="{StaticResource CellStyle0}" 
     HeaderStyle="{StaticResource HeaderStyle}"/>

我认为这 NotationType是来自与DataSpace.

让我知道这个是否奏效。


推荐阅读