简体   繁体   English

如何在DataGridTextColumn WPF XAML中将绑定值设置为TargetNullValue属性

[英]How do i set a Binding Value to a TargetNullValue property in a DataGridTextColumn WPF XAML

i'm trying to put a default value on my DataGridTextColumn in case the Binding Property gives Null Value, like and if in sql server... 我正在尝试在我的DataGridTextColumn上放一个默认值,以防Binding属性给出Null值,就像在SQL Server中一样。

So i researched and found the property TargetNullValue where can i put a default value in case the column have a null. 因此,我研究并找到了TargetNullValue属性,如果列为空,我可以在其中放置默认值。

But is not working as i am doing it. 但是不起作用,因为我正在这样做。 Throws me the next error 引发下一个错误

System.Windows.Markup.XamlParseException: 'A 'Binding' cannot be set on the 'TargetNullValue' property of type 'Binding'. System.Windows.Markup.XamlParseException:无法在类型为“绑定”的“ TargetNullValue”属性上设置“绑定”。 A 'Binding' can only be set on a DependencyProperty of a DependencyObject.' 只能在DependencyObject的DependencyProperty上设置'Binding'。

Here is a example of my XAML code. 这是我的XAML代码的示例。

<DataGrid x:Name="proveedorDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding IsAsync=True}" Margin="15,50,25,70" RowDetailsVisibilityMode="VisibleWhenSelected"
              SelectionMode="Single" IsReadOnly="True" CanUserAddRows="False" CanUserResizeRows="False" CanUserDeleteRows="False" PreviewKeyDown="ProveedorDataGrid_OnPreviewKeyDown">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="municipioColumn" Binding="{Binding Municipio, TargetNullValue={Binding CCodigoPostal.Municipio}}" Header="Municipio" Width="Auto" />
        </DataGrid.Columns>
    </DataGrid>

with the current resources 用当前资源

<Window.Resources>
    <CollectionViewSource x:Key="proveedorViewSource" d:DesignSource="{d:DesignInstance {x:Type Core:Proveedor}, CreateList=True}"/>
</Window.Resources>

Actually is binded with EntityFramework using DataSource... 实际上是使用DataSource与EntityFramework绑定的...

Thank you so much in advance! 提前非常感谢您!

*Updated CLASS *更新的CLASS

public class Proveedor
{
    public Proveedor()
    {
        ValeVehiculoCombustibles = new HashSet<ValeVehiculoCombustible>();
        FacturaProveedors = new HashSet<FacturaProveedor>();
        EntradaBasculas = new HashSet<EntradaBascula>();
    }

    public Guid? Id_Proveedor { get; set; }

    public string Codigo { get; set; }

    public string RazonSocial { get; set; }

    public string Calle { get; set; }

    public string Colonia { get; set; }

    public virtual C_CodigoPostal CCodigoPostal { get; set; }
    public int CCodigoPostalId { get; set; }

    public string Telefonos { get; set; }

    public string RFC { get; set; }

    public virtual CuentaContable CuentaContable { get; set; }
    public Guid? CuentaContableId { get; set; }

    public short DiasCred { get; set; }

    public decimal SaldoMN { get; set; }

    public decimal AnticipoMN { get; set; }

    public decimal SaldoDlls { get; set; }

    public decimal AnticipoDlls { get; set; }

    public string Contacto { get; set; }

    public string Email { get; set; }

    public string Municipio { get; set; }

    public string Estado { get; set; }

    public string Ciudad { get; set; }

    public bool Estatus { get; set; }

    public DateTime Actualizado { get; set; }

    public virtual ICollection<ValeVehiculoCombustible> ValeVehiculoCombustibles { get; set; }
    public virtual ICollection<FacturaProveedor> FacturaProveedors { get; set; }
    public virtual ICollection<EntradaBascula> EntradaBasculas { get; set; }
}

** And his configuration **和他的配置

public class ProveedorConfiguration : EntityTypeConfiguration<Proveedor>
{
    public ProveedorConfiguration()
    {
        ToTable("Proveedor");

        //PK
        HasKey(p => p.Id_Proveedor);

        Property(p => p.Id_Proveedor)
            .IsRequired()
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(p => p.Codigo)
            .IsRequired()
            .HasColumnType("varchar")
            .HasMaxLength(6);
        HasIndex(p => p.Codigo)
            .IsUnique();

        Property(p => p.RazonSocial)
            .IsRequired()
            .HasColumnType("varchar")
            .HasMaxLength(60);

        Property(p => p.Calle)
            .IsRequired()
            .HasColumnType("varchar")
            .HasMaxLength(40);

        Property(p => p.Colonia)
            .HasColumnType("varchar")
            .HasMaxLength(30);

        Property(p => p.CCodigoPostalId)
            .IsRequired()
            .HasColumnType("int");

        Property(p => p.Telefonos)
            .HasColumnType("varchar")
            .HasMaxLength(30);

        Property(p => p.RFC)
            .HasColumnType("varchar")
            .HasMaxLength(13);
        HasIndex(p => p.RFC)
            .IsUnique();

        Property(p => p.CuentaContableId)
            .IsRequired();

        Property(p => p.DiasCred)
            .IsRequired()
            .HasColumnType("smallint");

        Property(p => p.SaldoMN)
            .IsRequired()
            .HasColumnType("decimal")
            .HasPrecision(10, 2);

        Property(p => p.AnticipoMN)
            .IsRequired()
            .HasColumnType("decimal")
            .HasPrecision(10, 2);

        Property(p => p.SaldoDlls)
            .IsRequired()
            .HasColumnType("decimal")
            .HasPrecision(8, 2);

        Property(p => p.AnticipoDlls)
            .IsRequired()
            .HasColumnType("decimal")
            .HasPrecision(8, 2);

        Property(p => p.Contacto)
            .HasColumnType("varchar")
            .HasMaxLength(60);

        Property(p => p.Email)
            .HasColumnType("varchar")
            .HasMaxLength(90);

        Property(p => p.Municipio)
            .HasColumnType("varchar")
            .HasMaxLength(50);

        Property(p => p.Estado)
            .HasColumnType("varchar")
            .HasMaxLength(31);

        Property(p => p.Ciudad)
            .HasColumnType("varchar")
            .HasMaxLength(45);

        Property(p => p.Estatus)
            .IsRequired();

        //Relationships
        //FK Proveedor -> ValeVehiculoCombustible
        HasMany(p => p.ValeVehiculoCombustibles)
            .WithOptional(v => v.Proveedor)
            .HasForeignKey(v => v.ProveedorId)
            .WillCascadeOnDelete(false);

        //PK Proveedor -> FacturaProveedor
        HasMany(p => p.FacturaProveedors)
            .WithRequired(f => f.Proveedor)
            .HasForeignKey(f => f.ProveedorId)
            .WillCascadeOnDelete(false);

        //FK Proveedor -> EntradaBasucla
        HasMany(p => p.EntradaBasculas)
            .WithRequired(e => e.Proveedor)
            .HasForeignKey(e => e.ProveedorId)
            .WillCascadeOnDelete(false);
    }
}

** And finally, here is the returned result of the query at debug mode... **最后,这是调试模式下查询的返回结果...

ViewSource Result ViewSource结果

You can't bind to TargetNullValue . 您不能绑定到TargetNullValue You can only put a hard-coded value in there. 您只能在其中放置一个硬编码的值。 If you want to bind, you can use a DataGridTemplateColumn with a Textblock and use a DataTrigger on it to change the value. 如果要绑定,则可以将DataGridTemplateColumnTextblock使用, DataTrigger在其上使用DataTrigger来更改值。

So, default the Textblock to bind to Municipio , then if it's {x:Null} , then bind it to CCodigoPostal.Municipio . 因此,默认将Textblock绑定到Municipio ,然后将其绑定为{x:Null} ,然后将其绑定到CCodigoPostal.Municipio

<DataGrid.Columns>
    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Municipio}">
                     <TextBlock.Style>
                         <Style TargetType="TextBlock">
                             <Setter Property="Text" Value="{Binding Path=Municipio}"></Setter>
                             <Style.Triggers>
                                 <DataTrigger Binding="{Binding Path=Municipio}" Value="{x:Null}">
                                     <Setter Property="Text" Value="{Binding Path=CCodigoPostal.Municipio}"></Setter>
                                  </DataTrigger>
                              </Style.Triggers>
                          </Style>
                      </TextBlock.Style>
                  </TextBlock>
              </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
  </DataGrid.Columns>

If you want to go above and beyond (and do it right), you'd make a DataTemplate in your resources and just reference that instead of putting all the xaml right in-line. 如果您想超越(并做正确的事),则可以在资源中创建一个DataTemplate并仅引用它而不是将所有xaml放在一行。

If you want to use a resource, you would put the DataTemplate in your Windows.Resources . 如果要使用资源,则可以将DataTemplate放入Windows.Resources

 <Window.Resources>
        <DataTemplate x:Key="template">
            <TextBlock Text="{Binding Path=Municipio}">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="Text" Value="{Binding Path=Municipio}"></Setter>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Municipio}" Value="{x:Null}">
                                <Setter Property="Text" Value="{Binding Path=CCodigoPostal.Municipio}"></Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </DataTemplate>
    </Window.Resources>

Then, set the CellTemplate . 然后,设置CellTemplate

 <DataGrid x:Name="grid" Grid.Row="3">
            <DataGrid.Columns>
                <DataGridTemplateColumn CellTemplate="{StaticResource template}">
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当文本框的绑定设置为OneWayToSource时,WPF TargetNullValue返回值 - WPF TargetNullValue returning value when the textbox's binding is set to OneWayToSource 如何在DataGridTextColumn上将XAML中的双精度值格式化为德语格式? - How do I format a double value in XAML to German format on a DataGridTextColumn? 如何在绑定中将 TargetNullValue 设置为文件夹路径? - How to set TargetNullValue as folderpath in binding? 如何使用 WPF 中的代码绑定 DataGridTextColumn 的可见性属性? - How do I bind the visibility property of a DataGridTextColumn using code in WPF? 如何在代码中设置DataGridTextColumn的绑定? - How can I set the binding of a DataGridTextColumn in code? 如何在Visibility属性上执行简单的XAML(WPF)条件绑定 - How to do a simple XAML (WPF) conditional binding on the Visibility property WPF-如何根据绑定属性值设置行样式? - WPF - How do I style a row based on a binding property value? 如何在WPF中动态更改DataGridTextColumn绑定上的转换器? - How can I dynamically change the converter on DataGridTextColumn binding in WPF? 如何仅在WPF的Binding中使用xaml设置值? - How can I set the value using xaml only in WPF's Binding? WPF DataGridTextColumn FontWeight 绑定/值转换器不起作用 - WPF DataGridTextColumn FontWeight Binding / Value Converter not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM