简体   繁体   中英

Custom UserControl DependencyProperty Binding

I created a custom UserControl where among other controls I have the following

        <TextBlock Text="{Binding NameUtility}" />
        <TextBlock Text="{Binding TotalCost}" "/>

In the code both binding are declared as follows

    public static readonly DependencyProperty SetNameUtilityProperty =
        DependencyProperty.Register(
            nameof(NameUtility),
            typeof(string),
            typeof(SummaryInfo));

    public string NameUtility
    {
        get { return (string)GetValue(SetNameUtilityProperty); }
        set { SetValue(SetNameUtilityProperty, value); }
    }

    public static readonly DependencyProperty SetTotalCostProperty =
        DependencyProperty.Register(
            nameof(TotalCost),
            typeof(string),
            typeof(SummaryInfo));

    public string TotalCost
    {
        get { return (string)GetValue(SetTotalCostProperty); }
        set { SetValue(SetTotalCostProperty, value);  }
    }

The above control is used in another control XAML as

    <Utilities:SummaryInfo NameUtility="GAS" TotalCost="{Binding TotalGasEuro}"/>

The binded variable TotalGasEuro is correctly declare as follows

    private string _totalGasEuro;
    public string TotalGasEuro { get => _totalGasEuro; set { _totalGasEuro = value; NotifyPropertyChanged(); } }

When running the app, GAS shows up, while the binded value, which is updated on runtime, does not. (I removed from the code above graphical portions)

在此处输入图像描述

I found out my problem. Looks like to have a binding as the one I was trying to achieve, you need to specify the relative source.

In my case when calling the custom control from XAML:

    <Utilities:SummaryInfo NameUtility="GAS" TotalCost="{Binding TotalGasEuro, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM