Default datacontext

The presence of xaml below in MainWindow.xaml:

<Window x:Class="TestDependency.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
    <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Label Name="someLabel" Grid.Row="0"  Content="{Binding Path=LabelText}"></Label>
    <Button Grid.Row="2"  Click="Button_Click">Change</Button>
  </Grid>
</Window>

And the following code in MainWindow.xaml.cs:

public static readonly DependencyProperty LabelTextProperty = DependencyProperty.Register("LabelText", typeof(String), typeof(MainWindow));

public int counter = 0;

public String LabelText
{
  get
  {
    return (String)GetValue(LabelTextProperty);
  }

  set
  {
    SetValue(LabelTextProperty, value);
  }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
  LabelText = "Counter " + counter++;
}

I would think that the default DataContextis code. But I have to point out DataContext. Which DataContextis the default? Null? I would have thought that the code would have been (like the same class).

And as in this example, I use the code to change the contents of the label, can I use directly:

someLabel.Content = "Counter " + counter++;

I expect that, as the code behind, it should not have the UI update problem that you have if it DataContextis in another class.

+5
source share
2 answers

Yes, the default DataContextvalue is equal null, this is how it is declared in the class FrameworkElement-

public static readonly DependencyProperty DataContextProperty = 
    DependencyProperty.Register("DataContext", typeof(object),
    FrameworkElement._typeofThis,
    (PropertyMetadata) new FrameworkPropertyMetadata((object)null,
        FrameworkPropertyMetadataOptions.Inherits,
        new PropertyChangedCallback(FrameworkElement.OnDataContextChanged)));

FrameworkPropertyMetadata Value.

, lable DataContext null, .

someLabel.Content = "Counter " + counter++; codebehind ; , .

+5

Label, , , LabelText . , , Label MainWindow, , .

, " " " " : DataContext - , .

+3

All Articles