0

WPF has turned on Validation in TextBox by default. How could I propagate a TextBox's Validation.Error up to its ItemsControl if its ItemTemplate is composed of the TextBox ? I want to bind a button's IsEnabled into the Validation.Error on an item in ItemsControl.

            <ItemsControl ItemsSource="{Binding}"
                          x:Name="my_itemsControl">
                 <ItemsControl.ItemTemplate>
                        <DataTemplate>
                          <TextBox Text="{Binding FirstName}" />
                        </DataTemplate>
                 </ItemsControl.ItemTemplate>
            </ItemsControl>

            <Button Content="Save">
                <Button.IsEnabled >
                        <Binding ElementName="my_itemsControl"
                                 Path="(Validation.HasError)" />
                </Button.IsEnabled>
            </Button>
Jeff T.
  • 2,193
  • 27
  • 32

1 Answers1

0

OK, I finally got a nice solution which uses MVVM pattern.

       <UserControl x:Class="MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             x:Name="this_control">

             <Button Content="Save"
                     Command="{Binding Path=SaveCommand}"
                     CommandParameter="{Binding ElementName=this_control}" />
        </UserControl>

And the ICommand Property which I bound to on the view-model is like

    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(
                    param => save(),
                    param => IsValid((DependencyObject)param) // actually the type of param is MyUserControl
                );
            }
            return _saveCommand;
        }
    }

where the IsValid is based on the fantastic trick

Community
  • 1
  • 1
Jeff T.
  • 2,193
  • 27
  • 32