c# - 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}"/>
有人能帮忙吗?
解决方案
您是否尝试过在 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
.
让我知道这个是否奏效。
推荐阅读
- ruby-on-rails - 如何从 Rails 中的其他数据库表中呈现选项字段?
- typescript - TypeScript 是否能够对数字计算进行“const”断言?
- reporting-services - 将 SSRS 列组的 Null 结果放在最后
- python - 用于小型图像分类任务的 Conv2d 层数和过滤器数
- html - 证明内容似乎不会影响我的 flexbox 孩子。是因为我的元素之一的高度/宽度属性吗?
- python - 打印组合成连续字符串的输入字符串
- html - 相同的字体、字体粗细和浏览器,不同的网站,但给出不同的结果
- mysql - 从包含未知行数的表中选择前 25% 的行
- excel-formula - Google 表格 – 跨行计数
- jmeter - 了解 jmeter 结果 - 差异