Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd suggest that <code>element</code> should implement INotifyProperyChange and <code>myClass</code> 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).</p> <p>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.</p> <p><strong>UPDATE:</strong></p> <p>Here is indication of an error. Just changed item has border, duplicates for it - red font.</p> <pre><code>&lt;Style TargetType="{x:Type TextBox}"&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding Path=IsDuplicate}" Value="True"&gt; &lt;Setter Property="Foreground" Value="Red" /&gt; &lt;/DataTrigger&gt; &lt;Trigger Property="Validation.HasError" Value="true"&gt; &lt;Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/&gt; &lt;Setter Property="BorderBrush" Value="Red"/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>Here is item template, note <code>ValidatesOnDataErrors</code>:</p> <pre><code> &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid&gt; &lt;TextBox Text="{Binding Path=Name, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" /&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; </code></pre> <p>Here is your Element class:</p> <pre><code>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; } } } </code></pre> <p>And finally, <code>myClass</code> should listen to PropertyChanged and invoke duplication check.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload