none
WPF 后台创建列如何设置Converter? RRS feed

  • 问题

  • 前台代码:创建新列并绑定内容

    <Window x:Class="MethodConfiguration.ShowTable"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:MethodConfiguration;assembly="
            Title="ShowTable" Height="372" Width="892" Loaded="Window_Loaded">
        <Window.Resources>
            <local:DataSourceConvert x:Key="dataSourceConvert"/>
        </Window.Resources>
        <Grid x:Name="gridMain">
            <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" SelectionUnit="Cell">
                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="Background" Value="{Binding BackgroundColor,Converter={StaticResource dataSourceConvert}}"/>
                    </Style>
                </DataGrid.CellStyle>
            </DataGrid>
        </Grid>
    </Window>
    

    后台代码:

     
    void AddColumn(TimeUnit timeUnit)
            {
                //每个周期加一列
                string timeUnitName = "timeUnit" + newColumnIndex;
                string backgroundColor = "BackgroundColor";
                
                DataGridTextColumn dataGridTextColumnNew = new DataGridTextColumn() { Header = newColumnIndex.ToString(), Binding =new Binding( timeUnitName) };
    
                _dataGrid.Columns.Add(dataGridTextColumnNew);
                
    
                foreach (Step step in timeUnit.StepList)
                {
                    
                    string stepType;
                    switch(step.StepType)
                    {
                        case EStepType.ADDSAMPLESTEP:
                            stepType = "SMP";
                            break;
                        case EStepType.ADDMIDDLER1STEP:
                            stepType="MID";
                            break;
                        case EStepType.ADDACTIVATORR2STEP:
                            stepType="ACT";
                            break;
                        case EStepType.INCUBATIONSTEP:
                            stepType="INC";
                            break;
                        case EStepType.READTESTSTEP:
                            stepType="RED";
                            break;
                        case EStepType.DISPOSEWELL:
                            stepType="DIS";
                            break;
                        default:
                            stepType="NAN";
                            break;
                    }
                    
                    foreach (dynamic item in items)
                    {
                        if (step.Test.Patient.PatientCode == item.PatientCode)
                        {
                            //列标识,值
                            item.TrySetMember(new SetPropertyBinder(timeUnitName), stepType);
                            item.TrySetMember(new SetPropertyBinder(backgroundColor), stepType);
                            break;
                        }
                    }
                    
                }
            }
    public class DataSourceConvert : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                System.Console.WriteLine(value + " " + targetType + " " + parameter);
                switch ((string)value)
                {
                    case "SMP":
                        return new SolidColorBrush(Colors.Pink);
                    case "MID":
                        return new SolidColorBrush(Colors.Blue);
                    case "INC":
                        return new SolidColorBrush(Colors.Orange);
                    case "ACT":
                        return new SolidColorBrush(Colors.Green);
                    case "DIS":
                        return new SolidColorBrush(Colors.Gray);
                    case "RED":
                        return new SolidColorBrush(Colors.Yellow);
                    default:
                        return new SolidColorBrush(Colors.White);
                }
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotSupportedException();
            }
        }

    前台通过 <Style TargetType="DataGridCell">设置单元格样式,并绑定dataSourceConvert转换,

    后台中的数据包含各种类型,颜色应该,但是为什么所有颜色都是黄色? 怎样才能根据单元格内容区分颜色呢?

     

    2013年12月17日 6:29

答案

  • 您好!

    >>是不是有属性设置grid的什么模式选择整行或单元格? <<

    我们可以给一整行设置一个显示的样式。可以通过Style来实现。

    我调试了您的代码,运行效果是可以不同单元格显示不同信息的。我这边写了一个简化版的例子,您可以参考下:

    XAML Code:

    <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
    </Window.Resources>
    ...
    <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
            </Style>
        </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>

    Code Behind:

    public class NameToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string input = value as string;
            switch (input)
            {
                case "John":
                    return Brushes.LightGreen;
                default:
                    return DependencyProperty.UnsetValue;
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

    祝您生活愉快!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2013年12月23日 11:41
    版主

全部回复

  • 您好!

    我在本地创建了一个Project来还原这个问题,我建议您这样做,我们可以使用DataGridTemplateColumn替换DataGridTextColumn,并且将AutoGenerateColumns设置为false。具体请参考下面的代码:

    void AddColumn(TimeUnit timeUnit)
    {
       /* Create a DataGrid TemplateColumn */
       DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
       templateColumn.Header = templateColumn.DisplayIndex.ToString();
    
       /* Create Binding with Converter */
       Binding colorBinding = new Binding("BackgroundColor");
       colorBinding.Converter = new DataSourceConvert();
       colorBinding.Mode = BindingMode.OneWay;
    
       /* Create the Grid. Set the Background of the Grid to Color Binding */
       FrameworkElementFactory gridFactory = new FrameworkElementFactory(typeof(Grid));
       gridFactory.SetBinding(Grid.BackgroundProperty, colorBinding);
              
        /* Add a Textblock to display the Content */
        FrameworkElementFactory textBlockFactory 
                           = new FrameworkElementFactory(typeof(TextBlock));
        Binding textBinding = new Binding("BackgroundColor");
        textBinding.Mode = BindingMode.OneWay;
        textBlockFactory.SetBinding(TextBlock.TextProperty, textBinding);
    
        /* Add the TextBlock to Grid */
        gridFactory.AppendChild(textBlockFactory);
    
        /* Set the Grid to DataTemaplate */
        DataTemplate gridTemplate = new DataTemplate();
        gridTemplate.VisualTree = gridFactory;
    
        /* set the Cell Template of the Column to templateColumn */
        templateColumn.CellTemplate = gridTemplate;
    
        /* Add the Column to datagrid */
        _dataGrid.Columns.Add(templateColumn);
    
    
        /* Rest of your Code */
    }

    更多关于Converter的内容,请参考:

    http://wpftutorial.net/ValueConverters.html

    http://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/

    祝您生活愉快!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2013年12月18日 6:41
    版主
  • 显示颜色可以了.但是由于每行最后一个是DIS,整行的背景都被设置成DIS类型了.为什么会这样?

     void AddColumn(TimeUnit timeUnit)
            {
                string timeUnitName = "timeUnit" + newColumnIndex;
                foreach (dynamic item1 in items)
                {
                    item1.TrySetMember(new SetPropertyBinder(timeUnitName), "");
                }
                /* Create a DataGrid TemplateColumn */
                DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
                //templateColumn.Header = templateColumn.DisplayIndex.ToString();
                templateColumn.Header = newColumnIndex.ToString();
    
                /* Create Binding with Converter */
                Binding colorBinding = new Binding("BackgroundColor");
                colorBinding.Converter = new DataSourceConvert();
                colorBinding.Mode = BindingMode.OneWay;
    
                /* Create the Grid. Set the Background of the Grid to Color Binding */
                FrameworkElementFactory gridFactory = new FrameworkElementFactory(typeof(Grid));
                gridFactory.SetBinding(Grid.BackgroundProperty, colorBinding);
                
                /* Add a Textblock to display the Content */
                FrameworkElementFactory textBlockFactory
                                   = new FrameworkElementFactory(typeof(TextBlock));
                Binding textBinding = new Binding(timeUnitName);
                textBinding.Mode = BindingMode.OneWay;
                textBlockFactory.SetBinding(TextBlock.TextProperty, textBinding);
    
                /* Add the TextBlock to Grid */
                gridFactory.AppendChild(textBlockFactory);
    
                /* Set the Grid to DataTemaplate */
                DataTemplate gridTemplate = new DataTemplate();
                gridTemplate.VisualTree = gridFactory;
    
                /* set the Cell Template of the Column to templateColumn */
                templateColumn.CellTemplate = gridTemplate;
    
                /* Add the Column to datagrid */
                _dataGrid.Columns.Add(templateColumn);
    
    
                /* Rest of your Code */
    
                foreach (Step step in timeUnit.StepList)
                {
                    string stepType;
                    switch (step.StepType)
                    {
                        case EStepType.ADDSAMPLESTEP:
                            stepType = "SMP";
                            break;
                        case EStepType.ADDMIDDLER1STEP:
                            stepType = "MID";
                            break;
                        case EStepType.ADDACTIVATORR2STEP:
                            stepType = "ACT";
                            break;
                        case EStepType.INCUBATIONSTEP:
                            stepType = "INC";
                            break;
                        case EStepType.READTESTSTEP:
                            stepType = "RED";
                            break;
                        case EStepType.DISPOSEWELL:
                            stepType = "DIS";
                            break;
                        default:
                            stepType = "NAN";
                            break;
                    }
                    foreach (dynamic item in items)
                    {
                        if (step.Test.Patient.PatientCode == item.PatientCode)
                        {
                            item.TrySetMember(new SetPropertyBinder(timeUnitName), stepType);
                            //save the mark value in backgroundColor
                            item.TrySetMember(new SetPropertyBinder("BackgroundColor"), stepType);
                            break;
                        }
                    }
                }
            }
    这个是修改后的代码.是不是有属性设置grid的什么模式选择整行或单元格?
    2013年12月20日 6:29
  • 您好!

    >>是不是有属性设置grid的什么模式选择整行或单元格? <<

    我们可以给一整行设置一个显示的样式。可以通过Style来实现。

    我调试了您的代码,运行效果是可以不同单元格显示不同信息的。我这边写了一个简化版的例子,您可以参考下:

    XAML Code:

    <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
    </Window.Resources>
    ...
    <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
            </Style>
        </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>

    Code Behind:

    public class NameToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string input = value as string;
            switch (input)
            {
                case "John":
                    return Brushes.LightGreen;
                default:
                    return DependencyProperty.UnsetValue;
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

    祝您生活愉快!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2013年12月23日 11:41
    版主
  • 你的DataGrid中<DataGridTextColumn Binding="{Binding Name}">是在XAML中绑定的,但是我的列是在代码中创建的.

    所以我按照你的方式改XMAL的时候把Binding删除了(如下代码),然后就出现了错误,在绑定DataGrid的地方_dataGrid.ItemsSource = items;报错"在使用 ItemsSource 之前,项集合必须为空"。这是为什么呢?

    <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" SelectionUnit="Cell">
                <DataGridTextColumn>
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="{x:Type TextBlock}">
                            <Setter Property="Background" Value="{Binding BackgroundColor, Converter={StaticResource dataSourceConvert}}"/>
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
            </DataGrid>

    2013年12月25日 7:25
  • 我做化简了一下,做了一个解决方案能帮忙看下吗?

    skydrive共享:

    http://sdrv.ms/1fGmSLm

    • 已编辑 Lannykid 2013年12月25日 8:53 设置共享地址错误
    2013年12月25日 8:28
  • 你的压缩文件是空的。你直接用系统自带的压缩工具压缩下。然后重新上传到SkyDrive或者其他地方。
    2013年12月25日 10:44