0

I have a treeview in WPF and I bind the nodes via caliburn micro from a viewmodel.

I want to set a simple validation: when no node is selected, the treeview should be in error state and show a message, else not. For other controls like textbox or combobox I just set the validation properties in the view while binding and implement the IDataErrorInfo interface for the viewmodel. But I have no idea how to do this with the treeview.

My approach until now:

I create a validation rule for the tree to check if a treeview node is selected. The rule is executed, and seems to work, but I don't know how to activate validation in the Xaml. How do I activate validation for the treeview?

View:

<TreeView Name="Items" />

ViewModel:

public List<TreeViewItem> Items
{
  get { return mItems; }
  set
  {
    mItems= value;
    NotifyOfPropertyChange(() => Items);
  }
}

public string this[string columnName]
{
   get
   {
      if ((columnNames == "Items") && !Items.Any(x => x.IsSelected))
      {
         return "Error..";
      }
      ...
   }
}
StefanG
  • 1,234
  • 2
  • 22
  • 46

1 Answers1

1

Implement the INotifyDataErrorInfo interface in your view model, and define a Validation.ErrorTemplate for the TreeView in your view.

View:

<TreeView Name="Items" Margin="10">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <Grid>
                <Border BorderThickness="1" BorderBrush="Red">
                    <AdornedElementPlaceholder />
                </Border>
            </Grid>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TreeView>

View Model:

public class TreeViewModel : INotifyDataErrorInfo
{
    private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();

    public TreeViewModel()
    {
        Items = new List<TreeViewItem>();
        Items.Add(new TreeViewItem() { Header = "A" });
        Items.Add(new TreeViewItem() { Header = "B" });
        Items.Add(new TreeViewItem() { Header = "C" });
        Validate();
    }

    private List<TreeViewItem> mItems;
    public List<TreeViewItem> Items
    {
        get { return mItems; }
        set { mItems = value; Validate(); }
    }

    private void Validate()
    {
        if (!Items.Any(x => x.IsSelected))
            _validationErrors["Items"] = "error...";
        else
            _validationErrors.Remove("Items");
    }

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public bool HasErrors => _validationErrors.Any();

    public IEnumerable GetErrors(string propertyName)
    {
        string value;
        if (_validationErrors.TryGetValue(propertyName, out value))
            return new List<string>(1) { value };

        return null;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • The treeview has an error frame. That helped me, so I mark it as answer, also when the updating does not work. – StefanG Sep 25 '17 at 18:57