无法与我的控件使用双向绑定

本文关键字:绑定 控件 我的 | 更新日期: 2023-09-27 17:57:24

我是binding新手。我已slider值绑定到控件的属性,并且当我更改滑块值时,我的控件属性会更改。现在,当我需要通过更改我的属性值来更改滑块值时,它不起作用。

我从一些互联网资源修改了xaml,但仍然没有得到预期的输出。 谁能帮我...

<Grid>
    <cc:MyControl Name="mycntrl" ZoomPercentage="{Binding  ElementName=slider,Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></cc:MyControl>
    <Slider Name="slider"  Margin="20,20,20,400" Minimum="100" Maximum="400"></Slider>
</Grid>

更新:

我的 ZoomPercent 依赖项属性的代码隐藏如下

public double ZoomPercentage
    {
        get
        {
            return (double)GetValue(ZoomPercentageProperty);
        }
        set
        {
            SetValue(ZoomPercentageProperty, value);
        }
    }

我的依赖项注册

public static readonly DependencyProperty ZoomPercentageProperty = DependencyProperty.Register("ZoomPercentage", typeof(double), typeof(MyControl), new FrameworkPropertyMetadata(ZoomPercentagePropertyChanged));

public static void ZoomPercentagePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        if (args.OldValue != null)
        {
            if ((double)args.NewValue != (double)args.OldValue)
            {
                MyControl mycontrol = obj as MyControl;
                mycontrol .ZoomTo((int)((double)args.NewValue));
            }
        }
    }

无法与我的控件使用双向绑定

您的ZoomPercentage属性应实现为Dependencyproperty 像这样的东西

public class MyControl:UserControl 
{
  public MyControl() : base() { }
  public double ZoomPercentage
  {
    get { return (double)this.GetValue(ZoomPercentageProperty); }
    set { this.SetValue(ZoomPercentageProperty, value); } 
  }
  public static readonly DependencyProperty ZoomPercentageProperty = DependencyProperty.Register(
    "ZoomPercentage", typeof(double), typeof(MyControl:),new PropertyMetadata(0));
}

在此处阅读更多内容

如果希望 UI 中的数据绑定控件在代码中进行更改后更新,则必须执行以下两项操作之一。一种选择是在声明 Value 属性的类中正确实现 INotifyPropertyChanged 接口。

另一种是将您的Value属性声明为 DependencyProperty ,尽管您应该只在 WindowUserControl背后的代码中真正执行此操作,如果您使用的是视图模型,请选择第一种方法。这两种方法的目的是让你"插入"到 WPF 通知框架,以便 UI 控件将更新。请阅读链接页面以获取更多信息。