Domanda

Trying to understand how this code works:

Create dependency property,

public int YearPublished
{
    get { return (int)GetValue(YearPublishedProperty); }
    set { SetValue(YearPublishedProperty, value); }
}

public static readonly DependencyProperty YearPublishedProperty =
    DependencyProperty.Register(
        "YearPublished", 
        typeof(int), 
        typeof(SimpleControl), 
        new PropertyMetadata(2000));

Then use it in a form,

<xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <local:SimpleControl x:Name="_simple" />
    <TextBlock Text="{Binding YearPublished, ElementName=_simple}"
               FontSize="30"
               TextAlignment="Center" />
    <Button Content="Change Value"
            FontSize="20" 
            Click="Button_Click_1"/>
</StackPanel>

Then for Button_Click_1 do,

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    _simple.YearPublished++;
}

It works. Each time when you press the button, number must be changed from PropertyMetadata - from 2000++, but also I saw it on form in textBox.

Question: Why?

If I don't put any code for updating TextBlock in main Form, is it automatically updating or is there some hidden mechanism for it? Or maybe I do not fully understand how it works. Or maybe if its property there are features, that update the number on the form.

È stato utile?

Soluzione

When you created a DependencyProperty,

DependencyProperty.Register(
    "YearPublished", 
    typeof(int), 
    typeof(SimpleControl), 
    new PropertyMetadata(2000));

based on the YearPublished property, you are basically registering it with the DependencyProperty framework in a way that every time the property is read from or written to, it notifies all subscribers of the event that has taken place. You register it by specifying the name of the property i.e. "YearPublished", the property type, the type of the control where the property resides and, in this case the initial value of 2000.

By binding it to the TextBlock,

<TextBlock Text="{Binding YearPublished, ElementName=_simple}" />

you are letting the text block know when the property changes so it can update itself. When the YearPublished property changes, it notifies the text block of this change, which in turn retrieves the updated value and updates its Text property with it.

This is a very high level view, though, but enough to use it properly. To further understand the internals take a look at this MSDN post.

Altri suggerimenti

If the binding has the correct settings and the data provides the proper notifications, then, when the data changes its value, the elements that are bound to the data reflect changes automatically.

check this overview

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top