【问题标题】:Databinding and default values数据绑定和默认值
【发布时间】:2012-07-26 04:01:58
【问题描述】:

我拥有的是一个 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() } });

【问题讨论】:

  • 我会调查的!谢谢:)

标签: c# wpf data-binding datagrid


【解决方案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();
        }
    }
}

【讨论】:

  • 完美,正是我需要的,除了我从代码设置转换器(如果其他人想知道如何,请参见上面的示例)
猜你喜欢
  • 2015-04-16
  • 2012-05-21
  • 2016-10-07
  • 2017-01-07
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
相关资源
最近更新 更多