DataGridTextColumn显示按代码选择的描述

时间:2013-11-06 08:56:14

标签: c# wpf data-binding datagrid

在代码背后,我有一个代码列表,其中的描述是从数据库中提取的。 例如:{(code1,Description 1),(code2,Description 2)}

我将此Dictionary<string, string> StatusText存储在我的代码中。

页面的数据源是一个加载到XmlFile的xml文件,并设置为页面的数据上下文。 ReportsXmlFile的成员,是一个数组,是数据网格的源。

datagrid的“状态”列绑定到Reports.StatusCode。我需要使用StatusCodeStatusText中查找值,并在“状态”列中显示值部分。

现在我需要在DataGrid中显示代码值的相应描述,我几乎迷失了。 datagrid必须是不可编辑的,因此我更喜欢DataGridTextColumn或类似的列类型。

我对wpf比较新。

XAML

<Page x:Class="Project1.ApprovalQueue"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="ApprovalQueue" Loaded="Page_Loaded"
mc:Ignorable="d">
<Page.Resources>
    <uc:TextToVisiblityConvertor x:Key="TextToVisiblity" />
</Page.Resources>
<Page.DataContext>
    <h:XmlFile x:Name="XmlData" />
</Page.DataContext>
<Grid Name="GrdData" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">
    <DataGrid Name="DGrid" HorizontalAlignment="Stretch"
            AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False"
            CanUserSortColumns="False" HeadersVisibility="Column" IsReadOnly="True"         VerticalScrollBarVisibility="Auto" SelectionChanged="DGrid_SelectionChanged"
            ItemsSource="{Binding Path=Reports, NotifyOnSourceUpdated=True}">
        <DataGrid.Columns>
            <DataGridTemplateColumn x:Name="DueStatus" Width="16">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <!--  ReSharper disable Xaml.BindingWithContextNotResolved - This will be generated at Runtime  -->
                            <Image Source="{Binding ElementName=ImgOverDue, Path=Source}" Height="16" Width="16" Visibility="{Binding Converter={StaticResource TextToVisiblity}, Path=OverDue}"/>
                            <!--  ReSharper restore Xaml.BindingWithContextNotResolved  -->
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn x:Name="IncompleteStatus" Width="16">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <!--  ReSharper disable Xaml.BindingWithContextNotResolved - This will be generated at Runtime  -->
                            <Image Source="{Binding ElementName=ImgIncomplete, Path=Source}" Height="16" Width="16" Visibility="{Binding Converter={StaticResource TextToVisiblity}, Path=InComplete}"/>
                            <!--  ReSharper restore Xaml.BindingWithContextNotResolved  -->
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn x:Name="RptStatus" Width="100" Header="Status" Binding="{Binding Path=StatusCode}" />
            <DataGridTextColumn x:Name="RptDesc" Header="Report Description" Binding="{Binding Path=Description}"/>
            <DataGridTextColumn x:Name="RptState" Width="150" Header="Current State" />
            <DataGridTextColumn x:Name="RptDate" Width="100" Header="Submit Date" Binding="{Binding Path=SubmitDate}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>
</Page>

背后的代码

public partial class ApprovalQueue
{
    public Dictionary<string, string> StatusText = new Dictionary<string, string>();

    public ApprovalQueue()
    {
        InitializeComponent();

        DataTable dt = MyConnection.GetLookupData("GetTrans", "report_status", int.MinValue);
        foreach (DataRow row in dt.Rows)
        {
            StatusText.Add(Convert.ToString(row[0]), Convert.ToString(row[1]));
        }
        var fileInfo = new FileInfo(@"D:\XForms\APPQREFRESH.XML");
        ProcessAppQueue(ref fileInfo);
    }

    private void ProcessAppQueue(ref FileInfo fileInfo)
    {
        var serializer = new XmlSerializer(typeof (XmlFile));
        var reader = new StreamReader(fileInfo.FullName);
        XmlData = (XmlFile) serializer.Deserialize(reader);
        reader.Close();
        DGrid.ItemsSource = XmlData.Reports;
        Debug.WriteLine("here");
    }        

    private void DGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        //DataRow dRow = 
        //TxtDesc.Text = Convert.ToString(dSet.Tables["REPORT"].Rows[grid.CurrentRowIndex]["DESC"]);
    }
}

数据源

namespace Helper
{
    [Serializable]
    [XmlRoot("XML_FILE")]
    public class XmlFile : INotifyPropertyChanged
    {
        private Report[] _reports;

        [XmlArray("REPORTS")]
        [XmlArrayItem("REPORT", typeof (Report))]
        public Report[] Reports
        {
            get { return _reports; }
            set
            {
                if (value != _reports)
                {
                    _reports = value;
                    NotifyPropertyChanged("Reports Changed");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }

    [Serializable]
    public class Report : INotifyPropertyChanged
    {
        private string _reportType;

        [XmlAttribute("TYPE")]
        public string ReportType
        {
            get { return _reportType; }
            set
            {
                if (value != _reportType)
                {
                    _reportType = value;
                    NotifyPropertyChanged("ReportType");
                }
            }
        }

        [XmlElement("FILE")]
        public string FileName { get; set; }

        [XmlElement("S_DT")]
        public string SubmitDate { get; set; }

        [XmlElement("STAT")]
        public string StatusCode { get; set; }

        [XmlElement("OVER")]
        public string OverDue { get; set; }

        [XmlElement("INCM")]
        public string InComplete { get; set; }

        [XmlElement("DESC")]
        public string Description { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

好的,所以你的问题是你试图展示与你的DataGrid数据绑定的集合中不存在的东西。答案很简单......将其添加到集合中。这是之前将其设置为DataGrid.ItemsSource的一种方式:

foreach (Report report in Reports)
{
    report.StatusCode = StatusText[report.StatusCode];
}

这将使用描述替换StatusCode属性中的代码。如果您不想替换该值,那么您只需在Report类中添加一个额外的列:

public string StatusDescription { get; set; }