C# SetBinding()和属性={Binding Path}之间的差异
我有一个自定义控件,它有一个名为“VerticalOffset”的DependencyProperty,它有一个公共getter和一个私有setter。然后我尝试将它绑定到ScrollViewer.VerticalOffset,它是它的模板的一部分C# SetBinding()和属性={Binding Path}之间的差异,c#,wpf,C#,Wpf,我有一个自定义控件,它有一个名为“VerticalOffset”的DependencyProperty,它有一个公共getter和一个私有setter。然后我尝试将它绑定到ScrollViewer.VerticalOffset,它是它的模板的一部分 public static readonly DependencyProperty VerticalOffsetProperty = DependencyProperty.Register("VerticalOffset", typeof(d
public static readonly DependencyProperty VerticalOffsetProperty = DependencyProperty.Register("VerticalOffset", typeof(double), typeof(MyControl));
public double HorizontalOffset
{
get { return (double)GetValue(HorizontalOffsetProperty); }
private set
{
SetValue(HorizontalOffsetProperty, value);
}
}
我尝试了两种解决方法,但事情变得很奇怪
public override void OnApplyTemplate()
{
PART_ScrollViewer = (ScrollViewer)GetTemplateChild("PART_ScrollViewer");
this.SetBinding(VerticalOffsetProperty, new Binding("VerticalOffset") { Source = PART_ScrollViewer });
}
这两种解决方案有什么区别?为什么第二种不起作用?毕竟,我尝试了SetBinding()和SetValue()方法在定义类范围之外验证我的假设,即私有setter在代码级别没有意义。结果表明,直接使用SetBinding()或SetValue()方法更改属性值,无论其属性setter是私有的还是公共的 但是,如果我们使用私有setter,那么xaml中的任何值设置都是禁止的,这意味着我们不能使用VerticalOffset=“20”或VerticalOffset=“{Binding Path}”语法 此外,我还尝试了WPF核心只读属性,如ScrollViewer.VerticalOffseProperty,结果非常有趣 错误:没有授权密钥,无法修改只读VerticalOffsetProperty 然后SetBinding()方法返回另一个结果 错误:“VerticalOffset”为只读,无法绑定 我想 1.因为我们定义了DependencyProperty,所以我们拥有在代码级别使用SetValue()或SetBinding()方法修改它的全部权限,而包装器被忽略,因为它只是一个lite接口,与CLR属性一样,是一个通用接口。所以,当我们使用私有setter时,xaml将失败 2.也许.net的开发人员已经发现了这些潜在的风险,所以他们使用了一些验证方法来避免无效的更改
你有哪个VS版本?我的没有正确地缩写“因为”。@AustinMullins:vs2013,使用.net4.0.Ok。你是说第一个代码块中的VerticalOffset吗?@AustinMullins:是的,第一个在code behind中,第二个在xaml中。不,我是说第一个发布HorizontalOffset依赖属性的块。
VerticalOffset="{Binding VerticalOffset,ElementName=PART_ScrollViewer}"