【问题标题】:DataGrid Column Width string to width converter MVVMDataGrid 列宽字符串到宽度转换器 MVVM
【发布时间】:2019-08-11 00:23:48
【问题描述】:
现在我有一个具有多个不同条目的ComboBox,并且选择时,我想要一个DataGrid我必须根据来自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# wpf mvvm datagrid converters


    【解决方案1】:

    您是否尝试过在 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 相同项目的属性。

    让我知道这是否有效。

    【讨论】:

    • NotationType 是与数据空间不同的属性,它是同一网格内组合框的选定值绑定,因此我使用了 Width="{Binding Path=NotationType, RelativeSource={RelativeSource AncestorType=Grid} , UpdateSourceTrigger =PropertyChanged, IsAsync=True, Mode=TwoWay, Converter={StaticResource WidthConv}}" ,它仍然默认为 auto 而不是输入的值。
    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2011-10-05
    • 2018-08-31
    • 2015-03-20
    • 2011-04-01
    相关资源
    最近更新 更多