数据绑定和默认值

时间:2012-07-25 19:22:05

标签: c# wpf data-binding datagrid

我拥有的是DataGrid(在 WPF 中),我已将其绑定到我所做的自定义类的列表中。

让我们说,为简单起见,课程如下:

public class MyClass{

   int val;
   string str;
   static const int alwaysSetValue = 10;

}

有没有办法(在数据绑定或类本身中)说“如果val = -1,在数据网格中而不是显示-1,只显示空白,或''?

我正在查看Binding的IsTargetNull值,如果int是可以为空的类型,那会很好,但我宁愿不使用int?如果可能的话。

有没有办法做到这一点?某种覆盖ToString()或什么?

解决方案 见下面的答案。我做的唯一改变是设置绑定&转换为代码:

DataGrid.Columns.Add(new DataGridTextColumn() { Header = "Value", Binding = new Binding("val") { Converter = new MyValConverter() } });

1 个答案:

答案 0 :(得分:1)

以下是示例:

XAML文件:

<Window x:Class="DataGridConverter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:local="clr-namespace:DataGridConverter"
        >
    <Window.Resources>
        <local:MyValConverter x:Key="myCon" />
    </Window.Resources>
    <Grid>
        <DataGrid Name="grid" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Val" Binding="{Binding val, Converter={StaticResource myCon}}" />
                <DataGridTextColumn Header="Str" Binding="{Binding str}" />               
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

代码隐藏文件:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;

namespace DataGridConverter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<MyClass> _source = new List<MyClass>();
            for (int i = 0; i < 5; i++)
            {
                _source.Add(new MyClass { val = 1, str = "test " + i });
            }

            _source[2].val = -1;

            grid.ItemsSource = _source;
        }
    }

    public class MyClass
    {
        public int val { get; set; }
        public string str { get; set; }
        const int alwaysSetValue = 10;
    }

    public class MyValConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (int)value == -1 ? string.Empty : value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}