Binding Binding Binding Binding Class

Definition

Defines a binding that connects the properties of binding targets and data sources.

public : class Binding : BindingBase, IBinding, IBinding2public class Binding : BindingBase, IBinding, IBinding2Public Class Binding Inherits BindingBase Implements IBinding, IBinding2// This API is not available in Javascript.
<Binding .../>
Inheritance
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Inherited Members

Inherited methods

Inherited properties

Examples

The following code example demonstrates how to create a binding in XAML. For the complete code listing, see the XAML data binding sample.

<StackPanel Margin="5">

  <TextBlock Text="Name:" Style="{StaticResource DescriptionTextStyle}" 
    Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

  <TextBox Text="{Binding Path=Name, Mode=TwoWay}" 
    Width="350" Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

  <TextBlock Text="Organization:" Style="{StaticResource DescriptionTextStyle}" 
    Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

  <!-- You can omit the 'Path=' portion of the binding expression. --> 
  <TextBox Text="{Binding Organization, Mode=TwoWay}" Width="350" 
    Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

</StackPanel>

The following example code demonstrates how to create a binding in code.

// Create the source string.
string s = "Hello";

// Create the binding description.
Binding b = new Binding();
b.Mode = BindingMode.OneTime;
b.Source = s;

// Attach the binding to the target.
MyText.SetBinding(TextBlock.TextProperty, b);
// Create the source string.
String^ s = ref new String(L"Hello");

// Create the binding description.
Binding^ b = ref new Binding();
b->Mode = BindingMode::OneTime;
b->Source = s;

// Attach the binding to the target.
MyText->SetBinding(MyText->TextProperty, b);
'Create the source string 
Dim s As String = "Hello"

'Create the binding description 
Dim b As New Binding()
b.Mode = BindingMode.OneTime
b.Source = s

'Attach the binding to the target 
MyText.SetBinding(TextBlock.TextProperty, b)

Remarks

The {Binding} markup extension enables you to specify a Binding value as a single attribute string in XAML, including setting Binding properties such as Path and Source. For more info about data binding concepts, see Data binding in depth.

The Binding class might be considered the code-behind exposure of the {Binding} markup extension. If a binding is already applied to a target (which happens when the XAML is loaded), you can't set the read-write properties of a Binding object to change how a binding behaves at run-time. Any XAML-defined binding should be considered immutable. But you can create a new Binding object, set its properties, and establish a new binding on a specific UI element target using FrameworkElement.SetBinding. For more info, see Creating bindings in code.

A Binding object connects a dependency property of a FrameworkElement directly to a data object so that updates to the data object are automatically propagated to the property that uses data binding. The Binding class defines the properties of a binding. Each binding must have a target element, target property, and data source, although some values are provided by default if you don't specify them.

To bind to a property or a sub-property on a data object, set the Path property of the Binding object. For more info on how to set Path in code or in XAML, see Property-path syntax or {Binding} markup extension.

You can apply an instance of a Binding class to multiple targets. However, you cannot modify the property values of a Binding object after you attach it to a target element.

Note

Calling the FrameworkElement.SetBinding method and passing in a new Binding object won't necessarily remove an existing binding. Instead, you should use the DependencyObject.ClearValue method.

For more info on XAML attribute usage for properties that can take a Binding, or that can otherwise be set to a data-bound value, see {Binding} markup extension.

The property that is the target of a data binding must be a dependency property. For more info, see Dependency properties overview.

Constructors

Binding() Binding() Binding() Binding()

Initializes a new instance of the Binding class.

public : Binding()public Binding()Public Sub New()// This API is not available in Javascript.
See Also

Properties

Converter Converter Converter Converter

Gets or sets the converter object that is called by the binding engine to modify the data as it is passed between the source and target, or vice versa.

public : IValueConverter Converter { get; set; }public IValueConverter Converter { get; set; }Public ReadWrite Property Converter As IValueConverter// This API is not available in Javascript.
<Binding Converter="converterReference"/>

Examples

To use your converter in a binding, first create an instance of your converter class. The following example shows this as a resource in a XAML file.

<UserControl.Resources>
  <local:DateToStringConverter x:Key="Converter1"/>
</UserControl.Resources>
<TextBlock Grid.Column="0" Margin="5,0"
  Text="{Binding Month, Converter={StaticResource Converter1}}"/>
// Custom class implements the IValueConverter interface.
public class DateToStringConverter : IValueConverter
{

    #region IValueConverter Members

    // Define the Convert method to change a DateTime object to 
    // a month string.
    public object Convert(object value, Type targetType, 
        object parameter, string language)
    {
        // The value parameter is the data from the source object.
        DateTime thisdate = (DateTime)value;
        int monthnum = thisdate.Month;
        string month;
        switch (monthnum)
        {
            case 1:
                month = "January";
                break;
            case 2:
                month = "February";
                break;
            default:
                month = "Month not found";
                break;
        }

        // Return the month value to pass to the target.
        return month;
    }

    // ConvertBack is not implemented for a OneWay binding.
    public object ConvertBack(object value, Type targetType, 
        object parameter, string language)
    {
        throw new NotImplementedException();
    }

    #endregion
}
' Custom class implements the IValueConverter interface.
Public Class DateToStringConverter
    Implements IValueConverter

    ' Define the Convert method to change a DateTime object to
    ' a month string.
    Public Function Convert(ByVal value As Object, _
        ByVal targetType As Type, ByVal parameter As Object, _
        ByVal language As System.String) As Object _
        Implements IValueConverter.Convert

        ' value is the data from the source object.
        Dim thisdate As DateTime = CType(value, DateTime)
        Dim monthnum As Integer = thisdate.Month
        Dim month As String
        Select Case (monthnum)
            Case 1
                month = "January"
            Case 2
                month = "February"
            Case Else
                month = "Month not found"
        End Select
        ' Return the value to pass to the target.
        Return month

    End Function

    ' ConvertBack is not implemented for a OneWay binding.
    Public Function ConvertBack(ByVal value As Object, _
        ByVal targetType As Type, ByVal parameter As Object, _
        ByVal language As System.String) As Object _
        Implements IValueConverter.ConvertBack

        Throw New NotImplementedException

    End Function
End Class

Remarks

Create a converter by implementing the IValueConverter interface and implementing the Convert method. That method should return an object that is of the same type as the dependency property that the binding targets, or at least a type that can be implicitly coerced or converted to the target type.

See Also

ConverterLanguage ConverterLanguage ConverterLanguage ConverterLanguage

Gets or sets a value that names the language to pass to any converter specified by the Converter property.

public : PlatForm::String ConverterLanguage { get; set; }public string ConverterLanguage { get; set; }Public ReadWrite Property ConverterLanguage As string// This API is not available in Javascript.
<Binding ConverterLanguage="string"/>
Value
PlatForm::String string string string

A string that names a language. Interpretation of this value is ultimately up to the converter logic.

Remarks

If a value for ConverterLanguage is specified, this value is used for the language value when invoking the converter logic. Specifically, this provides the value of the language parameter of the Convert or ConvertBack methods of the specific converter that is requested with the Converter property. By default and in the absence of ConverterLanguage being set, the value passed for language is an empty string.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

ConverterParameter ConverterParameter ConverterParameter ConverterParameter

Gets or sets a parameter that can be used in the Converter logic.

public : PlatForm::Object ConverterParameter { get; set; }public object ConverterParameter { get; set; }Public ReadWrite Property ConverterParameter As object// This API is not available in Javascript.
<Binding ConverterParameter="parameter"/>
-or-
<Binding ConverterParameter="parameterReference"/>
Value
PlatForm::Object object object object

A parameter to be passed to the Converter. This can be used in the conversion logic. The default is null.

Remarks

Passing parameters to a converter is a relatively advanced and uncommon scenarios. Most converters used for data binding simply type-convert a source object to a desired target type based solely on the characteristics of the source object, and knowing what the intended destination type is for a particular binding scenario.

If a value for ConverterParameter is specified, this value is used for the parameter value when invoking the converter logic. Specifically, this provides the value of the parameter parameter of the Convert or ConvertBack methods of the specific converter that is requested with the Converter property.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

ElementName ElementName ElementName ElementName

Gets or sets the name of the element to use as the binding source for the Binding.

public : PlatForm::String ElementName { get; set; }public string ElementName { get; set; }Public ReadWrite Property ElementName As string// This API is not available in Javascript.
<Binding ElementName="nameString"/>
Value
PlatForm::String string string string

The value of the Name property or x:Name attribute for the element you want to use as the binding source. The default is an empty string.

Examples

The following code example demonstrates how to establish a two-way binding between a TextBox and a Slider control. For the complete code listing, see scenario 1 in the XAML data binding sample.

<Slider x:Name="slider1" Minimum="1" Maximum="100"/>
<TextBox Text="{Binding ElementName=slider1, Path=Value, Mode=TwoWay}"/>

Remarks

When you set this property, the specified value must refer to an element in one of the following locations:

  • The current XAML namescope.
  • The XAML namescope of the templated parent if the binding target is in a data template or control template. Because of this restriction, you cannot use the ElementName property to bind to elements that are not created by using XAML. To bind to elements created programmatically, use the Source property instead. Source, RelativeSource, and ElementName are mutually exclusive in a binding. If you have set one of these attributes, then setting either of the other two in a binding (through XAML or through code) will cause an exception.

Bindings that use an ElementName value almost always include a simple Path that names a property that exists on the object being referenced. It's common that the source property from the named element and the destination property on the target have the same name and use the same value type, this is a scenario you see fairly often in control template definitions that composite control parts but surface properties from the parts. If the source and destination properties use different types, specify a Converter value that can resolve the type difference and return an appropriate value for the destination.

For more info about XAML namescopes and how they influence bindings and other programmatic access to objects created from XAML, see XAML namescopes.

The value of ElementName can technically be any string, but the values of Name and x:Name attribute are enforced to be valid in the XamlName grammar, so you're typically bound by that grammar for an ElementName value too. For more info on what's valid for an element name, see the "XamlName grammar" section in the x:Name attribute reference.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

FallbackValue FallbackValue FallbackValue FallbackValue

Gets or sets the value to use when the binding is unable to return a value.

public : PlatForm::Object FallbackValue { get; set; }public object FallbackValue { get; set; }Public ReadWrite Property FallbackValue As object// This API is not available in Javascript.
<Binding FallbackValue="fallbackValue" />
Value
PlatForm::Object object object object

The value to use when the binding is unable to return a value.

Remarks

Usually you specify FallbackValue for bindings that display strings in UI. For this case the FallbackValue is also a string. You might want to use a resource so that it's easier to localize this string.

If you do specify a literal string for FallbackValue, you must use alternate quotes for the FallbackValue value within the {Binding} markup extension usage if your string contains spaces, because the {Binding} markup extension usage for an attribute is already within quotes. For example, <object property="{Binding FallbackValue='A literal string'}" />.

If used within a {Binding} markup extension usage, the value for FallbackValue can use any implicit string conversions that are already available to XAML, such as treating 0 as a string for a string binding, or converting enum values. For example, <object property="{Binding Path=Visibility, FallbackValue=Collapsed}" /> is valid because the parser can evaluate the string "Collapsed" and return Visibility.Collapsed as the fallback for a Visibility value.

TargetNullValue is a similar property with similar scenarios. The difference is that a binding uses FallbackValue for cases where the Path doesn't evaluate on the data source at all, or if attempting to set it on the source with a two-way binding throws an exception that's caught by the data binding engine. FallbackValue is also used if the source value is the dependency property sentinel value DependencyProperty.UnsetValue. A binding uses TargetNullValue if the Path and Source do evaluate, but the value found there is null.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

Mode Mode Mode Mode

Gets or sets a value that indicates the direction of the data flow in the binding.

public : BindingMode Mode { get; set; }public BindingMode Mode { get; set; }Public ReadWrite Property Mode As BindingMode// This API is not available in Javascript.
<Binding Mode="bindingModeMemberName"/>
Value
BindingMode BindingMode BindingMode BindingMode

One of the BindingMode values. The default is OneWay: the source updates the target, but changes to the target value do not update the source.

Examples

This example demonstrates how to set the binding mode in XAML.

<TextBox x:Name="MyTextBox" Text="Text" Foreground="{Binding Brush1, Mode=OneWay}"/>

Remarks

For OneWay and TwoWay bindings, dynamic changes to the source don't automatically propagate to the target without providing some support from the source. You must implement the INotifyPropertyChanged interface on the source object so that the source can report changes through events that the binding engine listens for. For C# or Microsoft Visual Basic, implement System.ComponentModel.INotifyPropertyChanged. For Visual C++ component extensions (C++/CX), implement Windows::UI::Xaml::Data::INotifyPropertyChanged.

For TwoWay bindings, changes to the target automatically propagate to the source, except if the binding target is the TextBox.Text property. In that case, the update happens only when the TextBox loses focus. Also, it's possible to set UpdateSourceTrigger on TwoWay bindings to Explicit, in which case you control the updates to the source explicitly by calling UpdateSource.

For OneTime and OneWay bindings, calls to DependencyObject.SetValue automatically change the target value and delete the binding.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

Path Path Path Path

Gets or sets the path to the binding source property.

public : PropertyPath Path { get; set; }public PropertyPath Path { get; set; }Public ReadWrite Property Path As PropertyPath// This API is not available in Javascript.
<Binding Path="propertyPath"/>
Value
PropertyPath PropertyPath PropertyPath PropertyPath

The property path for the source of the binding.

Examples

The following XAML demonstrates how to set the Path using the {Binding} markup extension. For the complete code listing, see the XAML data binding sample.

<StackPanel Margin="5">

  <TextBlock Text="Name:" Style="{StaticResource DescriptionTextStyle}" 
    Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

  <TextBox Text="{Binding Path=Name, Mode=TwoWay}" 
    Width="350" Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

  <TextBlock Text="Organization:" Style="{StaticResource DescriptionTextStyle}" 
    Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

  <!-- You can omit the 'Path=' portion of the binding expression. -->
  <TextBox Text="{Binding Organization, Mode=TwoWay}" Width="350" 
    Margin="5" HorizontalAlignment="Left" VerticalAlignment="Top"/>

</StackPanel>

The following XAML demonstrates how to set the Path using integer and string indexers. For the complete code listing, see the XAML data binding sample.

Note

Visual C++ component extensions (C++/CX) does not currently support indexer binding. See the sample for a workaround.

<StackPanel>

  <StackPanel Orientation="Horizontal">

    <TextBlock Text="Team name:" 
      Style="{StaticResource DescriptionTextStyle}" 
      Margin="5" FontWeight="Bold"/>

    <TextBlock Text="{Binding Path=[3].Name}" 
      Style="{StaticResource DescriptionTextStyle}" Margin="5" />

  </StackPanel>

  <StackPanel Orientation="Horizontal">

    <TextBlock Text="Team manager:" 
      Style="{StaticResource DescriptionTextStyle}" 
      Margin="5" FontWeight="Bold"/>

    <TextBlock Text="{Binding Path=[3][Gaffer]}" 
      Style="{StaticResource DescriptionTextStyle}" Margin="5"/>

  </StackPanel>

</StackPanel>

Remarks

The path can be a direct property of the source object, or sub-properties of that object that you traverse to using the property path syntax. For Microsoft .NET data sources, paths can also use an indexer syntax to reference specific items in a collection. For details on the property path format, see Property-path syntax.

To set the data source to be the Source object, the path should be defined with an empty string ("").

When using the {Binding} markup extension, the Path value can be set using the argument immediately following the {Binding part of the extension usage, you don't need to explicitly include Path=. For example, {Binding Albums} sets the Path value of that binding to be a PropertyPath constructed from the string "Albums" (no other Binding properties are set).

Most usages of Path involve setting its value. For scenarios where you are getting the value to examine the properties of an existing binding, the PropertyPath.Path value contains the string that represents the path.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

RelativeSource RelativeSource RelativeSource RelativeSource

Gets or sets the binding source by specifying its location relative to the position of the binding target. This is most often used in bindings within XAML control templates.

public : RelativeSource RelativeSource { get; set; }public RelativeSource RelativeSource { get; set; }Public ReadWrite Property RelativeSource As RelativeSource// This API is not available in Javascript.
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
-or-
<Binding RelativeSource="{RelativeSource Self}"/>

Value
RelativeSource RelativeSource RelativeSource RelativeSource

The relative location of the binding source to use. The default is null.

Examples

This XAML example is taken from the generic.xaml file that defines the default visual states for all XAML controls. This particular segment is one of the visual states for the ToggleSwitch control. Here, one of the animations defined by the visual state references properties of the control that exist specifically so that templates can access them and get run-time values that modify the animation. For the template XAML to get properties from the control where the template is applied, the binding must use {RelativeSource TemplatedParent} as the RelativeSource value.

<VisualStateGroup x:Name="ToggleStates">
  <VisualStateGroup.Transitions>
    <VisualTransition x:Name="DraggingToOnTransition"
      From="Dragging"
      To="On"
      GeneratedDuration="0">
      <Storyboard>
        <RepositionThemeAnimation TargetName="SwitchKnob" 
          FromHorizontalOffset="
          {Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplateSettings.KnobCurrentToOnOffset}"
        />
        <RepositionThemeAnimation TargetName="SwitchCurtain"
          FromHorizontalOffset="
          {Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplateSettings.CurtainCurrentToOnOffset}"
        />
      </Storyboard>
    </VisualTransition>
...
  </VisualStateGroup.Transitions>
</VisualStateGroup>

Remarks

Source, RelativeSource, and ElementName are mutually exclusive in a binding. If you have set one of these attributes, then setting either of the other two in a binding (through XAML or through code) will cause an exception. Setting RelativeSource in XAML always requires the use of the {RelativeSource} markup extension. This is also true if you are creating the entire binding as a {Binding} markup extension, in which case the {RelativeSource} markup extension is nested within the RelativeSource component of the expression.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

Source Source Source Source

Gets or sets the data source for the binding.

public : PlatForm::Object Source { get; set; }public object Source { get; set; }Public ReadWrite Property Source As object// This API is not available in Javascript.
<Binding Source="sourceReference"/>
Value
PlatForm::Object object object object

The source object that contains the data for the binding.

Examples

The following code example demonstrates how to set this property in XAML. For the complete code listing, see the XAML data binding sample.

<StackPanel>

  <StackPanel.Resources>
    <CollectionViewSource x:Name="teamsCVS"/>
  </StackPanel.Resources>

  <ListBox x:Name="lbTeams" Height="200" 
    ItemsSource="{Binding Source={StaticResource teamsCVS}}">
    <ListBox.ItemTemplate>
      <DataTemplate><!-- ... --></DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

</StackPanel>

For an example demonstrates how to set this property in code, see the Binding class.

Remarks

The Source property is optional on a Binding object. If the Source property is set on a Binding object, the data source applies only to the target properties that use that Binding object.

To create a data source that is inherited by all the child elements in the tree, instead set the DataContext property on the parent element. Then the parent element and all its children look to the DataContext as the source of their bindings. If the Source is set for a child element, it will override the DataContext inheritance in that instance.

The target can bind directly to the Source object if the path is empty or to a property of the Source object as defined by the path. The path is set either in XAML with the binding syntax or when the Binding object is created.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

TargetNullValue TargetNullValue TargetNullValue TargetNullValue

Gets or sets the value that is used in the target when the value of the source is null.

public : PlatForm::Object TargetNullValue { get; set; }public object TargetNullValue { get; set; }Public ReadWrite Property TargetNullValue As object// This API is not available in Javascript.
<Binding TargetNullValue="nullValueString" />
Value
PlatForm::Object object object object

The value that is used in the binding target when the value of the source is null.

Remarks

TargetNullValue might be used for bindings that bind a collection and the source data uses null for missing info only in some of the items. It might also be used for general cases where the data is coming from a database that uses null values as source info to signify something, such as a record that needs more info from the user and isn't complete in the source.

There are two recommended patterns for using TargetNullValue behavior in a Binding:

  • The binding source provides a separate value that is accessed by a different path, which acts as the singleton value that can substitute for any null value coming from a specific data item in the source. For example:

    <Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue={Binding Path=NullValue}}"/>
    

    Here, NullValue is the path to the substitute value, and is referenced by another Binding.

  • Use resources to provide a value that's specific to your app in cases where the data source provided null and has no suitable property in another path to use as the substitution value. For example, ```xaml

    
    Here, `AppStringForNullInAStringABinding` is a resource string something like "(value not available)" that lets the user know that there should be data there in most of the data but this particular item didn't have that data from its source. Use resources so that the value can be localized.
    
    
    
    

FallbackValue is a similar property with similar scenarios. The difference is that a binding uses FallbackValue for cases where the Path and Source doesn't evaluate on the data source at all, or if attempting to set it on the source with a two-way binding throws an exception. It uses TargetNullValue if the Path does evaluate, but the value found there is null.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

UpdateSourceTrigger UpdateSourceTrigger UpdateSourceTrigger UpdateSourceTrigger

Gets or sets a value that determines the timing of binding source updates for two-way bindings.

public : UpdateSourceTrigger UpdateSourceTrigger { get; set; }public UpdateSourceTrigger UpdateSourceTrigger { get; set; }Public ReadWrite Property UpdateSourceTrigger As UpdateSourceTrigger// This API is not available in Javascript.
<Binding UpdateSourceTrigger="updateSourceTriggerMemberName"/>
Value
UpdateSourceTrigger UpdateSourceTrigger UpdateSourceTrigger UpdateSourceTrigger

One of the UpdateSourceTrigger values. The default is Default, which evaluates as a PropertyChanged update behavior.

Remarks

Your other choice for an UpdateSourceTrigger behavior is to set the value to be Explicit. When a two-way binding has its UpdateSourceTrigger value as Explicit, you must explicitly call UpdateSource on the relevant BindingExpression to cause the changed target values to update the data source. Use GetBindingExpression to get a BindingExpression from an object where a Binding to a dependency property exists and that binding is a two-way binding with UpdateSourceTrigger="Explicit".

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

See Also

See Also