WPF What conditions must be met in order to use data binding in user control elements?

I am going to create a custom control - specifically a pie chart. I want the markup to look something like this:

<c:PieChart>
    <!-- These dependency properties are never set -->
    <c:Slice Value="{Binding RedCount}" />
    <c:Slice Value="{Binding BlueCount}" />
    <c:Slice Value="{Binding GreenCount}" />
</c:PieChart>

PieChartcomes from Control:

[ContentProperty("Slices")]
public class PieChart : Control
{
    public PieChart()
    {
        Slices = new ObservableCollection<Slice>();
    }

    public ObservableCollection<Slice> Slices { get; private set; }
}

The aforementioned XAML causes the property to Slicespopulate with three instances Slice.

Here's a snippet from Slice:

public class Slice : ContentControl
{
    public static DependencyProperty ValueProperty
        = DependencyProperty.Register(
            "Value", typeof(double), typeof(Slice),
            new PropertyMetadata((p,a) => ((Slice)p).OnValueChanged(a)));

    private void OnValueChanged(DependencyPropertyChangedEventArgs e)
    {
        // This code never called!
    }
}

The problem is that the property Valueis Slicenever set. If I put the dependency property in PieChartand copied the binding expression, then the value will be set, so I'm sure that I understand the basics of dependency and binding properties.

, , ? , - , - , ?

" " , , , , .

, DataContext PieChart , RedCount .. , ( - ), VS . .

+3
2

, Slice . -, WPF , PieChart. :

PieChart AddLogicalChild, Slice. Slice . : MSDN : " , . ContentControl, ItemsControl HeaderedItemsControl."

PieChart a Panel. Slice , , Children , - PieChart. ; (. ). , , , .

PieChart a ItemsControl GetContainerForItemOverride, IsItemItsOwnContainerOverride , , PrepareContainerForItemOverride / Slice. (Cf. ListBox ListBoxItem, ComboBox ComboBoxItem ..). , ItemsSource DataTemplate (, ListBox) . ( Slice XAML , ListBoxItems XAML.)

, . RadialLayoutPanel ItemsControl, RadialLayoutPanel ItemsPanel.

+3

, , , , . , - :

<c:PieChart>
    <!-- These dependency properties are never set -->
    <c:Slice Value="{Binding RedCount, RelativeSource={AncestorType c:PieChart}}" />
    <c:Slice Value="{Binding BlueCount, RelativeSource={AncestorType c:PieChart}}" />
    <c:Slice Value="{Binding GreenCount, RelativeSource={AncestorType c:PieChart}}" />
</c:PieChart>

, , , , . . . (, :))

0

Source: https://habr.com/ru/post/1707210/


All Articles