我的问题是什么?它不起作用 (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>
答案 0 :(得分:1)
如果您绑定DependencyProperty
上的MainWindow
而非DataContext
,则可以使用'FindAncestor'绑定
<TextBox Text="{Binding ImgPosition, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type View:MainWindow}}, UpdateSourceTrigger=PropertyChanged}" />