Поделиться через


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.

Атрибуты

Примеры

Следующий пример является частью приложения, которое запрашивает у пользователя ввод нескольких клиентов и назначение представителя по продажам каждому клиенту, а затем проверяет, принадлежит ли представитель продаж и клиент одному региону. В примере задано ItemBindingGroupItemsControlValidationRuleзначение , AreasMatchбудет проверяться каждый элемент. В примере также создается ошибка Label проверки. Обратите внимание, что объект ContentLabel привязан к 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"/>

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

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 элементов.

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