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.
source
share