Aaginor
Aaginor

Reputation: 4782

Ensure unique items in List with Silverlight Databinding

in my Silverlight 4 application, I have a class myClass that contains a list of elements. This elements have a name-attribute that identifies them.

class element
{
  string Name { get; set; }
}

class myClass
{
  List<element> elements { get; }
}

To display the list of elements, I databind myClass.elements to a Silverlight-Listbox:

<ListBox>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <TextBox Text="{Binding Name, FallbackValue=[None], Mode=TwoWay,
                       NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
...

This way, changes to the Name of the element is automatically propagated back. But: I need to make sure, that the Name is unique in myClass.elements (and some more constraints, depending on properties of myClass.

Naturally, the elements doesn't know who contains it (and it shouldn't know, I think). So my problem is: How can I check the contraints of the elements (in the setter of the Name-property)? I'd really like to use the Silverlight-Databinding, because it already implements Error Notification.

Thanks in advance,
Frank

Upvotes: 1

Views: 407

Answers (1)

mikalai
mikalai

Reputation: 1736

I'd suggest that element should implement INotifyProperyChange and myClass should be listening to changes, then checking for duplications, either throwing exceptions or indicating an error though IDataErrorInfo, INotifyDataErrorInfo or custom indicator. (so you implement Observer pattern, I assume, myClass here is an observer for its items).

For custom way, it's possible to set "IsDuplicate" property in duplicate items and bind it to background (red) color. That could be more useful for user, if s/he intentionally wants to set duplicate name here and then wants to fix some item entered before. Also if would be easier to find duplicates if you indicate all of them in the list.

UPDATE:

Here is indication of an error. Just changed item has border, duplicates for it - red font.

<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsDuplicate}" Value="True">
            <Setter Property="Foreground" Value="Red" />
        </DataTrigger>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, 
               Path=(Validation.Errors)[0].ErrorContent}"/>
            <Setter Property="BorderBrush" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

Here is item template, note ValidatesOnDataErrors:

    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBox Text="{Binding Path=Name, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>

Here is your Element class:

class Element : INotifyPropertyChanged, IDataErrorInfo
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value;
        if(PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
        }
    }

    private bool _isDuplicate;
    public bool IsDuplicate
    {
        get { return _isDuplicate; }
        set
        {
            _isDuplicate = value;
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs("IsDuplicate"));
        }
    }
    //IDataErrorInfo
    public event PropertyChangedEventHandler PropertyChanged;

    public string this[string columnName]
    {
        get 
        {
            if (IsDuplicate)
                return "Duplicate col" + columnName;
            return null;
        }
    }

    public string Error
    {
        get { return null; }
    }
}

And finally, myClass should listen to PropertyChanged and invoke duplication check.

Upvotes: 1

Related Questions