简体   繁体   中英

How to set binding options in wpf DataGridCells that are auto generated?

I use IDataErrorInfo and DataAnnotations in my ViewModels to take care of validation and I want to use them for validation in my DataGrid . The behaviour I want for my cells can be simulated easily in a TextBox :

<TextBox Name="TestBox"
    Text="{Binding TextProperty, UpdateSourceTrigger=PropertyChanged, 
    ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>

However, in my DataGrid , the columns are automatically generated, and I can't set the ValidatesOnDataErrors binding option as I could if they were defined manually.

What I would like to do is something along these lines in a Style, since I don't want to alter the Binding's value, only its Binding Options:

<Style TargetType="DataGridCell">
    <Setter Property="Content" Value="{Binding Path=., UpdateSourceTrigger=PropertyChanged, 
    ValidatesOnDataErrors=True, NotifyOnValidationError=True}"/>
</Style>

But this doesn't work. I am not sure what Property to use in the setter, as the DataGridCell has an internal TextBox or TextBlock , and what exactly handles the cell's validation.

Any ideas?

On your datagrid, hook the "AutoGeneratingColumn" event.

Inside the event handler, you can use e.Column to get to the binding and adjust it. You'll have to cast e.Column to the correct type first though (DataGridTextColumn, for example).

<DataGrid AutoGenerateColumns="True" Name="dg" AutoGeneratingColumn="dg_AutoGeneratingColumn" />

Code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        dg.ItemsSource = new List<MyItem>() { new MyItem() { Item1 = "Item 1", Item2 = "Item 2" } };
    }

    private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        var tc = e.Column as System.Windows.Controls.DataGridTextColumn;
        var b = tc.Binding as System.Windows.Data.Binding;

        b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        b.ValidatesOnDataErrors = true;
        b.NotifyOnValidationError = true;
    }
}

public class MyItem
{
    public string Item1 { get; set; }
    public string Item2 { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM