将具有依赖属性的值从一个类绑定到wpf中的另一个类文本框控件

时间:2016-11-24 23:41:31

标签: wpf data-binding dependency-properties

我有两个类Radial.xaml.cs和ToothDimension.xaml.cs,想要将类Radial.xaml.cs文本框控件的值绑定到另一个类ToothDimension.xaml.cs的依赖属性,它可以正常工作。它没有受到文本框控制的约束。我是否需要在Radial.xaml.cs中更改DataContext?我试过这个:

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

2 个答案:

答案 0 :(得分:0)

请将绑定的路径更改为ToothHeight

<TextBlock x:Name="Length" Text="{Binding ToothHeight}" HorizontalAlignment="Left" Height="35"/>

虽然我建议你使用MVVM模式。

答案 1 :(得分:0)

它正确绑定,我开始工作了。