C# 无法对我的控件使用双向绑定

C# 无法对我的控件使用双向绑定,c#,wpf,xaml,binding,slider,C#,Wpf,Xaml,Binding,Slider,我不熟悉绑定。我已将slider值绑定到控件的属性,当我更改slider值时,我的控件属性将发生更改。 现在,当我需要通过更改属性值来更改滑块值时,它不起作用 我从一些internet源代码修改了xaml,但仍然没有得到预期的输出。 有人能帮我吗 <Grid> <cc:MyControl Name="mycntrl" ZoomPercentage="{Binding ElementName=slider,Path=Value, Mode=TwoWay, UpdateS

我不熟悉
绑定
。我已将
slider
值绑定到控件的属性,当我更改slider值时,我的控件属性将发生更改。 现在,当我需要通过更改属性值来更改滑块值时,它不起作用

我从一些internet源代码修改了
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>
我的依赖项注册

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
属性应作为 像这样的

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中的数据绑定控件,则必须执行以下两项操作之一。一个选项是在声明
值的类中正确实现

另一种方法是将
属性声明为,尽管您应该只在
窗口
用户控件
的代码隐藏中执行此操作,如果您使用的是视图模型,请选择第一种方法。这两种方法的目的是让您“插入”到WPF通知框架,以便更新UI控件。有关更多信息,请阅读链接页面

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