简体   繁体   English

自定义 UserControl DependencyProperty 绑定

[英]Custom UserControl DependencyProperty Binding

I created a custom UserControl where among other controls I have the following我创建了一个自定义UserControl在其他控件中我有以下

        <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上述控件在另一个控件XAML中使用为

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

The binded variable TotalGasEuro is correctly declare as follows绑定变量TotalGasEuro正确声明如下

    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.运行应用程序时, GAS会显示,而在运行时更新的绑定值不会显示。 (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:在我的情况下,当从 XAML 调用自定义控件时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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