Контекст данных по умолчанию

Имея приведенный ниже xaml в 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>

И следующий код в 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++;
}

Я бы подумал, что DataContextпо умолчанию является кодом позади. Но я вынужден указать DataContext. Который DataContextявляется по умолчанию?Null? Я бы подумал, что код, стоящий за ним, был бы (как и тот же класс).

И, как и в этом примере, я использую код для изменения содержимого Ярлык, могу ли я использовать напрямую:

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

Я ожидаю, что код позади, у него не должно быть проблем с обновлением пользовательского интерфейса, которые возникают у вас, если DataContextнаходится в другом классе.

6
задан akjoshi 24 November 2014 в 06:16
поделиться