Binding on DependencyProperty of custom User Control not updating on change

后端 未结 2 923
死守一世寂寞
死守一世寂寞 2021-01-17 13:16

I\'m having difficulties with databinding on my custom user control (s). I created an example project to highlight my problem. I\'m completely new to WPF and essentially MVV

相关标签:
2条回答
  • 2021-01-17 13:18

    I tried your code works fine the only change i made was to remove the code behind propertychangedcallback you have and databind the Label (Readout) to the dependency property.

    USERCONTROL(XAML)

    <UserControl x:Class="WpfApplication1.UserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
       <Grid>
           <Label Name="Readout" Content="{Binding RelativeSource={RelativeSource 
                                AncestorType=UserControl}, Path=MinutesRemaining}"/>
      </Grid>
    </UserControl>
    

    USERCONTROL (CODE BEHIND)

    public partial class UserControl1 : UserControl
    {
        #region Dependency Properties
        public static readonly DependencyProperty MinutesRemainingProperty =
                    DependencyProperty.Register
                    (
                        "MinutesRemaining", typeof(int), typeof(UserControl1),
                        new UIPropertyMetadata(10)
                    );
        #endregion
    
        public int MinutesRemaining
        {
            get
            {
                return (int)GetValue(MinutesRemainingProperty);
            }
            set
            {
                SetValue(MinutesRemainingProperty, value);
            }
        }
    
       public UserControl1()
        {
            InitializeComponent();
        }
    }
    
    0 讨论(0)
  • 2021-01-17 13:39

    Your change callback is breaking the binding.

    As a skeleton: in your window you have UC.X="{Binding A}" and then in that property change (in UC) you have X=B;. This breaks the binding since in both cases you set X.

    To rectify, remove change callback and add this to the label:

     Content="{Binding MinutesRemaining, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
    
    0 讨论(0)
提交回复
热议问题