移动到 UserControl 时无法使绑定工作

问题描述 投票:0回答:1

我们有一些想要重用的 XAML。在此示例中,我将其缩小为文本框。

<TextBlock Text="{Binding MyProperty.Value}"/>

我们想重用该组件,所以我将它放在 UserControl 中。 (不确定这是否是正确的方法)注意数据绑定仍然是相同的;

"{Binding MyProperty.Value}"

<controls:MyControl ControlValue="{Binding MyProperty.Value}"/>

该组件可以正常工作,因为如果我放置一个常量(例如

"25"
)而不是绑定,它就会按预期更新。 但它不会响应模型的变化。

为什么它在原始 XAML 中有效,但在 UserControl 中无效?我在这里缺少什么?

MyControl.xaml

<UserControl
    x:Class="Project.UI.Elements.Common.Controls.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Project.UI.Elements.Common.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="25"
    d:DesignWidth="100">

    <TextBlock Text="{Binding ControlProperty}"/>
</UserControl>

MyControl.xaml.cs

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236

namespace Project.UI.Elements.Common.Controls
{
    public sealed partial class MyControl : UserControl
    {
        public static readonly DependencyProperty ControlValueProperty =
            DependencyProperty.Register("BatteryLevel", typeof(double), typeof(BatteryLevelControl), new PropertyMetadata(0.0));

        public MyControl()
        {
            this.InitializeComponent();
            DataContext = this;
        }

        public double ControlValue
        {
            get { return (double)GetValue(ControlValue); }
            set { SetValue(ControlValue, value); }
        }
    }
}
c# xaml uwp
1个回答
0
投票

在 BatteryLevelControl 类中,将数据上下文设置为此。但是,由于该类派生自 UserControl,因此它不支持 INotifyPropertyChanged,因此不会收到任何更改。尝试将数据上下文设置为从 INotifyPropertyChanged 派生并包含依赖属性的类。

© www.soinside.com 2019 - 2024. All rights reserved.