DependencyProperty怎么样?

时间:2014-10-22 03:35:10

标签: c# wpf mvvm

我的问题是什么?它不起作用 (MVVM)

我得到空文本框,当我更改文本框文本时,不调用OnCurrentReadingChanged

namespace Test
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
        DataContext = new BaseModel();      
        this.InitializeComponent();           
    }
    public static DependencyProperty ImgPositionProperty = DependencyProperty.Register("ImgPosition", typeof(string), typeof(MainWindow),
     new PropertyMetadata("ddd", new PropertyChangedCallback(OnCurrentReadingChanged)));

    private static void OnCurrentReadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MessageBox.Show("1");
    }
  }
}

<Window xmlns:View="clr-namespace:Test">
  <Grid x:Name="LayoutRoot">
    <TextBox Margin="141,81,254,0" TextWrapping="Wrap" Text="{Binding View:MainWindow.ImgPosition, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top"/>
  </Grid>
</Window>

1 个答案:

答案 0 :(得分:1)

如果您绑定DependencyProperty上的MainWindow而非DataContext,则可以使用'FindAncestor'绑定

<TextBox Text="{Binding ImgPosition, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type View:MainWindow}}, UpdateSourceTrigger=PropertyChanged}" />