PropertyChangedEventHandler不起作用

本文关键字:不起作用 PropertyChangedEventHandler | 更新日期: 2023-09-27 18:30:10

我的UserControl xaml 中有一个下面的标签和一个滑块

<Label x:Name="labelValX" Content="{Binding Path=xValue}" HorizontalAlignment="Left" Width="88" Height="44"/>
 <Slider x:Name="sliderSpeed" Value="{Binding slideValue, Mode=TwoWay}" HorizontalAlignment="Left" Margin="10,35,0,0" VerticalAlignment="Top" Width="173" Height="53" Minimum="10" Maximum="100" />

和特定的SetGetAccValues.cs类:

public class SetGetAccValues : UserControl, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _xval;
    public string xValue
    {
        get { return _xval; }
        set
        {
            if (value != _xval)
            {
                _xval = value;
                OnPropertyChanged("xValue");
            }
        }
    }
    public byte _slideValue;  
    public byte slideValue {
            get
            {
                return _slideValue;
            }
            set
            {
                if (value != _slideValue)
                {
                    _slideValue = value;
                    OnPropertyChanged("slideValue");
                }
            }
          }

   protected virtual void OnPropertyChanged(string propName)
   {
      if (PropertyChanged != null)
       {
           PropertyChanged(this, new PropertyChangedEventArgs(propName));
           if (propName.Equals("slideValue"))
           {
           speedAccMeter(slideValue); 
           }
       }
   }

在我的另一个GetAccNotifications.cs类中,我有以下部分,我将xValue字符串定义为特定值:

Y = ((double)(sbyte)value) / 64.0;
Y = Math.Round(Y, 2);
SetGetAccValues set = new SetGetAccValues();
set.xValue = Y.ToString();

当以"xValue"作为propName触发OnPropertyChanged时,就会出现问题,PropertyChangedEventHandler始终为null,但当以"slideValue"作为propName触发时,它实际上不为null。为什么在xValue的情况下它保持为null?。

PropertyChangedEventHandler不起作用

我相信PropertyChanged事件在数据上下文加载完成之前就已启动。

您可以在用户控件中侦听DataContextChanged事件,这样当新的datacontext可用时,您就可以设置属性。

public AccView()
{
    InitializeComponent();
    this.DataContextChanged += OnDataContextChanged;
    this.DataContext = new SetGetAccValues();    
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
    Y = ((double)(sbyte)value) / 64.0;
    Y = Math.Round(Y, 2);
    (dependencyPropertyChangedEventArgs.NewValue as SetGetAccValues).xValue = Y.ToString();
}

我认为您没有绑定DataContext。您应该在您的案例中使用代码隐藏来设置DataContext。

In SetGetAccValues.xaml.cs

    public SetGetAccValues()
    {       
        DataContext = this;
    }