我有一个模型和一个窗口的视图模型,我被困在视图中 视图的控件具有以下内容:
<TextBlock Text="{Binding Title}" [...] />
数据上下文是视图模型,它具有string类型的Title
属性。
问题是,即使值发生变化(我可以通过调试器看到它)并且PropertyChanged
调用了Title
,TextBlock
也不会发生变化(它保持空白。)
为了确认这一点,我实际上每次按下鼠标都会调用更新方法。
我听说有时TextBlock
中的绑定被窃听,所以我也试过了一个标签,但它没有用。有什么建议?如果你想看到任何代码,请在评论中告诉我(整件事情都很大)。
ViewModel
Code-behind for the View.
更清楚:Window
是我的模特,而不是WPF的窗口!
答案 0 :(得分:1)
你的_window.Title是string.Empty。为它分配一些值。喜欢
public WindowViewModel()
{
Window = new Window(){Title="abc"};
}
更新我尝试了你的代码,但它对我没有用,我做了一个更改,它的工作变化是
public WindowEntryView()
{
DataContext = new WindowViewModel();
InitializeComponent();
}
答案 1 :(得分:1)
如果您实例化WindowViewModel
类
代码隐藏:
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>
答案 2 :(得分:0)
您能否将属性“Title”中的属性名称传递给OnPropertyChanged方法。