简体   繁体   中英

Property setter trims a value assigned from LINQ, but isn't displayed as such in WPF datagrid

I'm using LINQ to ODBC to project the results of a query, saved to an XML file, into a custom object. The custom object has a string property, "PayFrequency." Its setter trims the value assigned to it, if the value isn't null. I've opened my XML file and confirmed this works (the property value is trimmed).

However, when the custom object is deserialized and displayed in a WPF datagrid, the DataGridComboBoxColumn column value is blank for my property. The column's ItemsSource is bound to a StaticResource of string, which includes the value assigned to my custom object's PayFrequency property. So, why doesn't my value show in the datagrid?

The PayFrequency property:

    [XmlElement(IsNullable = true)]
    public string PayFrequency
    {
        get { return this.payFrequency; }
        set
        {
            if (value != this.payFrequency)
            {
                this.payFrequency = (value ?? value.Trim());
                NotifyPropertyChanged("PayFrequency");
            }
        }
    }

The WPF datagrid column:

<DataGridComboBoxColumn
    Header="Pay Frequency"
    SelectedItemBinding="{Binding XLGOCommission.PayFrequency, Mode=TwoWay}"
    ItemsSource="{Binding Source={StaticResource xlgoPayFrequencyStrings}}" />

The WPF datagrid column's ItemsSource:

   <x:Array Type="{x:Type sys:String}" x:Key="xlgoPayFrequencyStrings">
        <sys:String>APM</sys:String>
        <sys:String>APQ</sys:String>
        <sys:String>OD</sys:String>
        <sys:String>NP</sys:String>
    </x:Array>

An important point: If I trim the value in my LINQ query, rather than letting my custom object's setter property handle it, the value displays correctly in the WPF datagrid column. But, like I said, when I look at the custom object serialized to XML, there's no whitespace in the property value.

Here's my band-aid fix (excerpt from my LINQ query):

PayFrequency = xcom["pay_freq"].ToString().Trim()

Thanks for any help! I'd much rather encapsulate the manipulation of values assigned my custom object in the object itself, rather than "cleaining up" values elsewhere!

This line is not correct. It will only try to trim value if it's null, which will generate a runtime exception...

this.payFrequency = (value ?? value.Trim());

One way to trim it only if it's not null is to use the ternary operator instead...

if (value != this.payFrequency)
{
    this.payFrequency = (value == null ? "" : value.Trim());
    NotifyPropertyChanged("PayFrequency");
}

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