ItemsControl.ItemBindingGroup Свойство

Определение

Возвращает или задает объект BindingGroup, который копируется в каждый элемент в ItemsControl.

public:
 property System::Windows::Data::BindingGroup ^ ItemBindingGroup { System::Windows::Data::BindingGroup ^ get(); void set(System::Windows::Data::BindingGroup ^ value); };
[System.ComponentModel.Bindable(true)]
public System.Windows.Data.BindingGroup ItemBindingGroup { get; set; }
[<System.ComponentModel.Bindable(true)>]
member this.ItemBindingGroup : System.Windows.Data.BindingGroup with get, set
Public Property ItemBindingGroup As BindingGroup

Значение свойства

Объект BindingGroup, который копируется в каждый элемент в ItemsControl.

Атрибуты

Примеры

Следующий пример является частью приложения, которое предлагает пользователю ввести несколько клиентов и назначить торгового представителя каждому клиенту, а затем проверяет, принадлежат ли торговый представитель и клиент к одному региону. В этом примере задается ItemBindingGroup объект , ItemsControl поэтому ValidationRule, AreasMatchбудет проверять каждый элемент. В этом примере также создается объект , отображающий Label ошибки проверки. Обратите внимание, что Content объект Label объекта привязан к объекту , ValidationError который он получает из Validation.ValidationAdornerSiteForProperty свойства . Значение Validation.ValidationAdornerSiteForProperty — это контейнер элемента, в который возникла ошибка.

<ItemsControl Name="customerList"  ItemTemplate="{StaticResource ItemTemplate}"
              ItemsSource="{Binding}">
  <ItemsControl.ItemBindingGroup>
    <BindingGroup>
      <BindingGroup.ValidationRules>
        <src:AreasMatch/>
      </BindingGroup.ValidationRules>
    </BindingGroup>
  </ItemsControl.ItemBindingGroup>
  <ItemsControl.ItemContainerStyle>
    <Style TargetType="{x:Type ContentPresenter}">
      <Setter Property="Validation.ValidationAdornerSite"
              Value="{Binding ElementName=validationErrorReport}"/>
    </Style>
  </ItemsControl.ItemContainerStyle>
</ItemsControl>
<Label Name="validationErrorReport" 
       Content="{Binding RelativeSource={RelativeSource Self}, 
       Path=(Validation.ValidationAdornerSiteFor).(Validation.Errors)[0].ErrorContent}"
       Margin="5" Foreground="Red" HorizontalAlignment="Center"/>

В следующем примере возвращается контейнер элементов и вызывается UpdateSourcesBindingGroup для контейнера для проверки данных. Необходимо проверить данные, вызвав метод в контейнере элемента , а BindingGroupне ItemBindingGroupItemsControlв .

void saveCustomer_Click(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    FrameworkElement container = (FrameworkElement) customerList.ContainerFromElement(btn);

    // If the user is trying to change an items, when another item has an error,
    // display a message and cancel the currently edited item.
    if (bindingGroupInError != null && bindingGroupInError != container.BindingGroup)
    {
        MessageBox.Show("Please correct the data in error before changing another customer");
        container.BindingGroup.CancelEdit();
        return;
    }

    if (container.BindingGroup.UpdateSources())
    {
        bindingGroupInError = null;
        MessageBox.Show("Item Saved");
    }
    else
    {
        bindingGroupInError = container.BindingGroup;
    }
}
Private Sub saveCustomer_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim btn As Button = TryCast(sender, Button)
    Dim container As FrameworkElement = CType(customerList.ContainerFromElement(btn), FrameworkElement)

    ' If the user is trying to change an items, when another item has an error,
    ' display a message and cancel the currently edited item.
    If bindingGroupInError IsNot Nothing AndAlso bindingGroupInError IsNot container.BindingGroup Then
        MessageBox.Show("Please correct the data in error before changing another customer")
        container.BindingGroup.CancelEdit()
        Return
    End If

    If container.BindingGroup.UpdateSources() Then
        bindingGroupInError = Nothing
        MessageBox.Show("Item Saved")
    Else
        bindingGroupInError = container.BindingGroup
    End If

End Sub

Комментарии

При установке ItemBindingGroup свойства каждый контейнер элементов получает объект , который имеет BindingGroup те же ValidationRule объекты ItemBindingGroup, что и , но свойства, описывающие данные в привязках, такие как Items и BindingExpressions, относятся к данным для каждого элемента в ItemsControl. Необходимо получить доступ к контейнеру BindingGroup элементов для выполнения таких операций, как проверка данных и проверка на наличие ошибок в элементе.

Применяется к