WPF数据绑定和x:Array

3

我尝试使用资源中定义的x:Array进行一些数据绑定,但是不知何故,即使代码编译通过也无法正常工作。 在资源中,我用以下方式定义了一个字符串数组:

<x:Array x:Key="ArrayReportType" Type="{x:Type sys:String}">
    <sys:String>Energy Export</sys:String>
    <sys:String>Cost Center Report</sys:String>
</x:Array>

我还有一个对象集合。其中一个属性被称为“ReportType”,是一个整数/枚举类型。 因此,我想进行数据绑定,以显示与ReportType相应的字符串,而不是int/enum。 我尝试了这行代码,但它不起作用(第二行引起了问题):

我也有一个对象集合。其中一个属性被称为“ReportType”,是一个整数/枚举类型。 因此,我希望进行数据绑定,以显示与ReportType相应的字符串,而不是int/enum。 我尝试了以下代码,但它没有起作用(第二行引起了问题):

<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Type"
                    Binding="{Binding Source={StaticResource ArrayReportType}, Path=[{Binding ReportType}]}" />

我相信我已经接近解决方案了。如果我直接写“Path=[1]”,那么就是正确的。 但在运行时,我收到了以下错误信息:
System.Windows.Data Error: 40 : BindingExpression path error: '[]' property not found on 'object' ''String[]' (HashCode=14199578)'. BindingExpression:Path=[{Binding ReportType}]; DataItem='String[]' (HashCode=14199578); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
任何帮助都将不胜感激。
2个回答

1

也许你可以用专门的转换工具来解决这个问题。

类似这样的东西?

<DataGridTextColumn 
    Header="Type"
    Text="{Binding Converter={StaticResource IndexToArrayItemConverter}, ConverterParameter={StaticResource ArrayReportType}, Path=ReportType}"/>

转换器代码因为太明显而被跳过


好吧,这可能是一个解决方案,但是……我得写一个转换器!我想要一个100%的XAML解决方案! - Fred
我认为在纯XAML中没有办法做到这一点。Path=[?] 可能期望一个常量或属性,而不是绑定扩展。 - Nicolas Repiquet

1

可以使用DataGridComboBoxColumn吗?

<DataGridComboBoxColumn Header="Type"
                        ItemsSource="{Binding Source={StaticResource ArrayReportType}}">
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="SelectedIndex" Value="{Binding ReportType}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="SelectedIndex" Value="{Binding ReportType}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>

更新
只读文本单元格

<DataGridComboBoxColumn Header="Type"
                        ItemsSource="{Binding Source={StaticResource ArrayReportType}}"
                        IsReadOnly="True">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="SelectedIndex" Value="{Binding ReportType}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>

好的,这是我作为解决方法之一的想法。 但如果可能的话,我想要在单元格中“简单地”显示字符串。 WPF 是如此强大,应该是可能的! - Fred
是的,你比我快!!我刚刚看到,如果我将它设置为只读,那么下拉框就会显示为普通文本!非常感谢! - Fred
还有一个问题:我该如何使这一列可排序?在“SortMemberPath”中应该放什么? - Fred
@Fred:我试过了,当使用SortMemberPath="ReportType"时,它似乎可以正常工作。这会按索引升序/降序排序。你想如何排序? - Fredrik Hedblad
好的,那就是我的意思。我想按“字符串”排序,而不是按索引排序。 - Fred

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接