将具有依赖项属性的值从一个类绑定到wpf中的另一个类textbox控件
问题描述:
我有两个类Radial.xaml.cs和ToothDimension.xaml.cs,要将类Radial.xaml.cs的textbox控件的值绑定到另一个类ToothDimension.xaml.cs的依赖属性工作正常。它没有被绑定到文本框控件。我需要在Radial.xaml.cs中更改DataContext吗?我尝试这样做:将具有依赖项属性的值从一个类绑定到wpf中的另一个类textbox控件
Radial.xaml.cs
public Radial()
{
InitializeComponent();
DataContext = new ToothDimension();
}
Radial.xaml
<TextBlock x:Name="Length" Text="{Binding DataContext.ToothHeight}" HorizontalAlignment="Left" Height="35"/>
ToothDimension.xaml.cs(其中ToothHeight声明)
public Double ToothHeight
{
get { return (double)GetValue(ToothHeightProperty); }
set { SetValue(ToothHeightProperty, value); }
}
public static readonly DependencyProperty ToothHeightProperty
DependencyProperty.RegisterAttached("ToothHeight",
typeof(double), typeof(ToothDimensions),
new PropertyMetadata(new PropertyChangedCallback(ToothHeightChanged)));
private static void ToothHeightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
double value = (double)e.NewValue;
ToothMeasurements thisControl = d as ToothMeasurements;
}
答
请将您的绑定路径更改为ToothHeight
。
<TextBlock x:Name="Length" Text="{Binding ToothHeight}" HorizontalAlignment="Left" Height="35"/>
虽然我会建议你使用MVVM模式。
答
它绑定正确,我得到它的工作。
我用你提供的代码构建了一个应用程序 - 它的工作原理。尝试为您的依赖项属性设置另一个默认值,以确定是否存在绑定问题,或者您只是在更新您的Tooth-Height属性而挣扎。你的依赖属性看起来像这样:'公共静态只读DependencyProperty ToothHeightProperty = DependencyProperty.RegisterAttached(“ToothHeight”,typeof(double),typeof(ToothDimension),new PropertyMetadata(10.0,ToothHeightChanged));' – ManDani
ToothHeight关联到在Tooth Dimension类中的文本框,所以它工作正常。但是我想重复使用这个ToothHeight并将其绑定到Radial类中的另一个文本框控件。如果我使用ToothHeight绑定在同一个类中,我必须做的是DataContext = this在构造函数中。无法在Radial类中绑定。我在ToothDimension中有一个具有局部变量的构造函数。它看起来像这样。 public ToothDimension(int toothid) { InitializeComponent(); ToothId =齿状; } – user6850427
iam无法更新ToothHeight在另一个班级,我可以更新ToothHeight到同一班级的另一个文本框 – user6850427