绑定不';t响应PropertyChanged

本文关键字:响应 PropertyChanged 绑定 | 更新日期: 2023-09-27 18:26:26

我有一个Window的模型和一个视图模型,我被视图卡住了
该视图具有一个控件,该控件具有以下内容:

<TextBlock Text="{Binding Title}" [...] />

数据上下文是视图模型,它具有字符串类型的Title属性。

问题是,即使值发生了变化(我可以通过调试器看到它发生了变化),并且为Title调用了PropertyChangedTextBlock也不会发生变化(它保持为空)。

为了证实这一点,我实际上在每次按下鼠标时都调用了一个更新方法

我听说TextBlock中的绑定有时会出错,所以我也尝试过Label,但它不起作用。有什么建议吗?如果你想看任何代码,请在评论中告诉我(整个代码相当大)。

ViewModel
视图的代码隐藏。

更清楚地说:Window是我的模型,而不是WPF的Window

绑定不';t响应PropertyChanged

如果实例化WindowViewModel类,它会起作用

CodeBehind:

public partial class WindowEntryView
{
    public static readonly DependencyProperty WindowViewModelProperty;
    public WindowViewModel WindowViewModel
    {
        get { return (WindowViewModel)GetValue(WindowViewModelProperty); }
        set
        {
            SetValue(WindowViewModelProperty, value);
            value.Refresh(); // I've putted this out of desperation to see if it would help.. it didn't.
        }
    }
    static WindowEntryView()
    {
        PropertyMetadata metadata = new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender); // Another attempt with no success.
        WindowViewModelProperty = DependencyProperty.Register("WindowViewModel", typeof(WindowViewModel), typeof(WindowEntryView), metadata);
    }
    public WindowEntryView()
    {
        //WindowViewModel = new WindowViewModel(19860522); This is the only attempt that made the label show something, but it didn't update later of course.
        InitializeComponent();
        WindowViewModel = new WpfApplication3.WindowViewModel() { Title = "Check" };
        DataContext = WindowViewModel;
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        WindowViewModel.Title = DateTime.Now.ToString();
    }
}

XAML:

<Grid>
    <TextBlock Text="{Binding Title}" VerticalAlignment="Top"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="116,131,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>

您的_window.Title是字符串。空的给它分配一些价值。就像

public WindowViewModel()
{
    Window = new Window(){Title="abc"};
}

更新我试过你的代码,但对我不起作用我做了一个更改,它起作用了,更改是

public WindowEntryView()
{
    DataContext = new WindowViewModel();
    InitializeComponent();
}

请将属性名称(在您的情况下为"Title")传递给OnPropertyChanged方法。