FrameworkElement.BindingGroup 屬性

定義

取得或設定用於項目的 BindingGroupGets or sets the BindingGroup that is used for the element.

public:
 property System::Windows::Data::BindingGroup ^ BindingGroup { System::Windows::Data::BindingGroup ^ get(); void set(System::Windows::Data::BindingGroup ^ value); };
[System.Windows.Localizability(System.Windows.LocalizationCategory.NeverLocalize)]
public System.Windows.Data.BindingGroup BindingGroup { get; set; }
member this.BindingGroup : System.Windows.Data.BindingGroup with get, set
Public Property BindingGroup As BindingGroup

屬性值

用於項目的 BindingGroupThe BindingGroup that is used for the element.

屬性

範例

下列範例是應用程式的一部分,它會檢查使用者是否已將兩個物件的屬性設定為相等的值。The following examples are part of an application that checks whether the user has set the properties of two objects to equal values. 第一個範例會建立兩個 TextBox 控制項,其中每個都系結至不同的資料來源。The first example creates two TextBox controls, each of which is bound to a different data source. StackPanel 具有 BindingGroup,其中包含的 ValidationRule 會檢查兩個字串是否相等。The StackPanel has a BindingGroup that contains a ValidationRule that checks that the two strings are equal.

<StackPanel>
  <StackPanel.Resources>
    <src:Type1 x:Key="object1" />
    <src:Type2 x:Key="object2" />
  </StackPanel.Resources>

  <StackPanel Name="sp1"
              Margin="5"
              DataContext="{Binding Source={StaticResource object1}}"
              Validation.ValidationAdornerSite="{Binding ElementName=label1}"
              Orientation="Horizontal"
              HorizontalAlignment="Center">

    <StackPanel.BindingGroup>
      <BindingGroup Name="bindingGroup">
        <BindingGroup.ValidationRules>
          <src:BindingGroupValidationRule ValidatesOnTargetUpdated="True" />
        </BindingGroup.ValidationRules>
      </BindingGroup>
    </StackPanel.BindingGroup>

    <TextBlock Text="First string" />

    <TextBox Width="150"
             Text="{Binding Path=PropertyA}" />

    <TextBlock Text="Second string" />

    <TextBox Width="150"
             Text="{Binding Source={StaticResource object2}, 
      Path=PropertyB, BindingGroupName=bindingGroup, 
      TargetNullValue=please enter a string}" />

  </StackPanel>

  <Label Name="label1"
         Content="{Binding ElementName=sp1, Path=(Validation.Errors)[0].ErrorContent}"
         Margin="5"
         Foreground="Red"
         HorizontalAlignment="Center" />

  <Button HorizontalAlignment="Center"
          Click="Button_Click"
          IsDefault="True">
    _Submit
  </Button>

  <StackPanel Orientation="Horizontal">
    <TextBlock Text="First string:"
               FontWeight="Bold" />
    <TextBlock Text="{Binding Source={StaticResource object1}, 
      Path=PropertyA, TargetNullValue=--}" />
  </StackPanel>

  <StackPanel Orientation="Horizontal">
    <TextBlock Text="Second string:"
               FontWeight="Bold" />
    <TextBlock Text="{Binding Source={StaticResource object2}, 
      Path=PropertyB, TargetNullValue=--}" />
  </StackPanel>
</StackPanel>

下列範例顯示上一個範例所使用的 ValidationRuleThe following example shows the ValidationRule that the previous example uses. Validate 方法覆寫中,此範例會從 BindingGroup 取得每個來源物件,並檢查物件的屬性是否相等。In the Validate method override, the example gets each source object from the BindingGroup and checks whether the properties of the objects are equal.

public class Type1
{
    public string PropertyA { get; set; }

    public Type1()
    {
        PropertyA = "Default Value";
    }
}

public class Type2
{
    public string PropertyB { get; set; }

    public Type2()
    {
    }
}

public class BindingGroupValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        BindingGroup bg = value as BindingGroup;

        Type1 object1 = null;
        Type2 object2 = null;

        foreach (object item in bg.Items)
        {
            if (item is Type1)
            {
                object1 = item as Type1;
            }

            if (item is Type2)
            {
                object2 = item as Type2;
            }
        }

        if (object1 == null || object2 == null)
        {
            return new ValidationResult(false, "BindingGroup did not find source object.");
        }

        string string1 = bg.GetValue(object1, "PropertyA") as string;
        string string2 = bg.GetValue(object2, "PropertyB") as string;

        if (string1 != string2)
        {
            return new ValidationResult(false, "The two strings must be identical.");
        }

        return ValidationResult.ValidResult;
    }
}
Public Class Type1
    Public Property PropertyA() As String

    Public Sub New()
        PropertyA = "Default Value"
    End Sub
End Class

Public Class Type2
    Public Property PropertyB() As String

    Public Sub New()
    End Sub
End Class

Public Class BindingGroupValidationRule
    Inherits ValidationRule
    Public Overrides Function Validate(ByVal value As Object, ByVal cultureInfo As System.Globalization.CultureInfo) As ValidationResult
        Dim bg As BindingGroup = TryCast(value, BindingGroup)

        Dim object1 As Type1 = Nothing
        Dim object2 As Type2 = Nothing

        For Each item As Object In bg.Items
            If TypeOf item Is Type1 Then
                object1 = TryCast(item, Type1)
            End If

            If TypeOf item Is Type2 Then
                object2 = TryCast(item, Type2)
            End If
        Next item

        If object1 Is Nothing OrElse object2 Is Nothing Then
            Return New ValidationResult(False, "BindingGroup did not find source object.")
        End If

        Dim string1 As String = TryCast(bg.GetValue(object1, "PropertyA"), String)
        Dim string2 As String = TryCast(bg.GetValue(object2, "PropertyB"), String)

        If string1 <> string2 Then
            Return New ValidationResult(False, "The two strings must be identical.")
        End If

        Return ValidationResult.ValidResult

    End Function

End Class

若要叫用 ValidationRule,請呼叫 UpdateSources 方法。To invoke the ValidationRule, call the UpdateSources method. 下列範例會在按鈕的 click 事件發生時呼叫 UpdateSourcesThe following example calls UpdateSources when the click event of the button occurs.

private void Button_Click(object sender, RoutedEventArgs e)
{
    sp1.BindingGroup.UpdateSources();
}
Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    sp1.BindingGroup.UpdateSources()
End Sub

備註

BindingGroup 可以用來驗證物件的多個屬性值。A BindingGroup can be used to validate the values of multiple properties of an object. 例如,假設應用程式提示使用者輸入位址,然後將具有屬性 StreetCityZipCodeCountry的物件填入 Address,其中包含使用者提供的值。For example, suppose that an application prompts the user to enter an address and then populates an object of type Address, which has the properties Street, City, ZipCode, and Country, with the values that the user provided. 應用程式有一個面板,其中包含四個 TextBox 控制項,每個控制項都系結至物件的其中一個屬性。The application has a panel that contains four TextBox controls, each of which is bound to one of the object's properties. 您可以使用 BindingGroup 中的 ValidationRule 來驗證 Address 物件。You can use a ValidationRule in a BindingGroup to validate the Address object. 例如,ValidationRule 可以確保郵遞區號對位址的國家/地區有效。For example, the ValidationRule can ensure that the zip code is valid for the country/region of the address.

子專案會繼承其父元素的 BindingGroup,就像任何其他可繼承的屬性一樣。Child elements inherit the BindingGroup from their parent elements, just as with any other inheritable property.

相依性屬性資訊Dependency Property Information

識別碼欄位Identifier field BindingGroupProperty
設定為 true 的中繼資料屬性Metadata properties set to true Inherits

適用於