3

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

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

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

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

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

我听说有时TextBlocks 中的绑定有问题,所以我也尝试了 Label 但它没有用。有什么建议么?如果您想查看任何代码,请在评论中告诉我(整个事情很大)。

ViewModel 视图
的代码隐藏。

更清楚一点:Window是我的模型,而不是 WPF 的窗口!

4

3 回答 3

1

你的 _window.Title 是 string.Empty 。赋予它一些价值。喜欢

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

更新我尝试了您的代码,但它对我不起作用我做了一个更改并且它起作用了更改是

public WindowEntryView()
{
    DataContext = new WindowViewModel();
    InitializeComponent();
}
于 2013-08-04T11:52:44.767 回答
1

It would work if you instantiate your WindowViewModel class

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>
于 2013-08-04T11:55:14.830 回答
0

您能否将属性名称(在您的情况下为“Title”)传递给 OnPropertyChanged 方法。

于 2013-08-04T11:50:06.670 回答