para imagen emplea atributo c# wpf data-binding user-controls dependency-properties

c# - emplea - atributo title de la imagen



Enlace en DependencyProperty de User Control personalizado no actualizado en el cambio (2)

Intenté que tu código funcione bien, el único cambio que hice fue eliminar el código detrás de la devolución de propiedad cambiada que tienes y enlazar con la etiqueta (lectura) a la propiedad de la dependencia.

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 (CÓDIGO DETRÁS)

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(); } }

Tengo dificultades con los enlaces de datos en mis controles de usuario personalizados. Creé un proyecto de ejemplo para resaltar mi problema. Soy completamente nuevo en WPF y esencialmente MVVM también, así que tengan paciencia conmigo ...

Creé una vista simple que utiliza el enlace de datos de dos maneras. La unión de datos en el control integrado funciona bien. Mi control personalizado no ... Puse un punto de interrupción en PropertyChangedCallback de mi control. Se golpea una vez al inicio, pero nunca más. Mientras tanto, la etiqueta que he vinculado al mismo valor está felizmente en cuenta atrás.

¿Qué me estoy perdiendo? Mi ejemplo de proyecto sigue:

La ventana principal:

<Window x:Class="WpfMVVMApp.MainWindow" xmlns:local="clr-namespace:WpfMVVMApp" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.DataContext> <local:CountdownViewModel /> </Grid.DataContext> <Label Name="custName" Content="{Binding Path=Countdown.ChargeTimeRemaining_Mins}" Height="45" VerticalAlignment="Top"></Label> <local:UserControl1 MinutesRemaining="{Binding Path=Countdown.ChargeTimeRemaining_Mins}" Height="45"></local:UserControl1> </Grid> </Window>

Aquí está mi modelo:

namespace WpfMVVMApp { public class CountdownModel : INotifyPropertyChanged { private int chargeTimeRemaining_Mins; public int ChargeTimeRemaining_Mins { get { return chargeTimeRemaining_Mins; } set { chargeTimeRemaining_Mins = value; OnPropertyChanged("ChargeTimeRemaining_Mins"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }

El ViewModel:

namespace WpfMVVMApp { public class CountdownViewModel { public CountdownModel Countdown { get; set; } DispatcherTimer timer; private const int maxMins = 360; public CountdownViewModel() { Countdown = new CountdownModel { ChargeTimeRemaining_Mins = 60 }; // Setup timers timer = new DispatcherTimer(); timer.Tick += new EventHandler(this.SystemChargeTimerService); timer.Interval = new TimeSpan(0, 0, 1); timer.Start(); } private void SystemChargeTimerService(object sender, EventArgs e) { //convert to minutes remaining // DEMO CODE - TODO: Remove this.Countdown.ChargeTimeRemaining_Mins -= 1; } } }

Aquí está el XAML para mi control de usuario:

<UserControl x:Class="WpfMVVMApp.UserControl1" 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"></Label> </Grid> </UserControl>

Y aquí está el código detrás del control del usuario:

namespace WpfMVVMApp { public partial class UserControl1 : UserControl { #region Dependency Properties public static readonly DependencyProperty MinutesRemainingProperty = DependencyProperty.Register ( "MinutesRemaining", typeof(int), typeof(UserControl1), new UIPropertyMetadata(10, new PropertyChangedCallback(minutesRemainChangedCallBack)) ); #endregion public int MinutesRemaining { get { return (int)GetValue(MinutesRemainingProperty); } set { SetValue(MinutesRemainingProperty, value); } } static void minutesRemainChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args) { UserControl1 _readout = (UserControl1)property; _readout.MinutesRemaining = (int)args.NewValue; _readout.Readout.Content = _readout.MinutesRemaining; } public UserControl1() { InitializeComponent(); } } }


Su devolución de llamada de cambio está rompiendo el enlace.

Como esqueleto: en su ventana tiene UC.X="{Binding A}" y luego en ese cambio de propiedad (en UC) tiene X=B; . Esto rompe el enlace ya que en ambos casos configura X

Para rectificar, elimine el cambio de devolución de llamada y agréguelo a la etiqueta:

Content="{Binding MinutesRemaining, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"