C# 更改ViewModel对象不会反映对视图的更改
我已经实现了一个用户控件,在该控件中,我将C# 更改ViewModel对象不会反映对视图的更改,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我已经实现了一个用户控件,在该控件中,我将DataContext绑定到它自己,如下所示 this.DataContext = this; this.CurrentViewModel = viewModel; this.DataContext = this; 用户控件顶部有一个组合框。在它的选择更改事件上。我正在更新UserControl的属性,这将导致重新生成整个视图,包括TabControl和文本框中的一些选项卡 在选择更改事件中,我正在更新如下属性 this.DataContext =
DataContext
绑定到它自己,如下所示
this.DataContext = this;
this.CurrentViewModel = viewModel;
this.DataContext = this;
用户控件顶部有一个组合框。在它的选择更改事件上。我正在更新UserControl
的属性,这将导致重新生成整个视图,包括TabControl
和文本框中的一些选项卡
在选择更改事件中,我正在更新如下属性
this.DataContext = this;
this.CurrentViewModel = viewModel;
this.DataContext = this;
下面是视图中的一些示例xaml
<TextBox
x:Name="txtPageSetupAlias"
Width="500"
Padding="2,5,0,0"
Text="{Binding Path=CurrentViewModel.ValidPageSetupAlias, Mode=TwoWay}"
Style="{StaticResource ResourceKey=txtAlias}" DockPanel.Dock="Left"
/>
<TabControl
x:Name="tcOrientation"
Grid.Row="1"
BorderBrush="Transparent"
BorderThickness="0"
Margin="0,0,0,0"
TabStripPlacement="Top"
ItemsSource="{Binding Path=CurrentViewModel.Orientations}">
谁能告诉我我在这里错过了什么
更新2:
共享组合选择更改事件:
private void cmbPageSetupTemplate_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_errors = 0;
var validPageSetup = cmbPageSetupTemplate.SelectedItem as PageSetupEditorViewModel;
CurrentViewModel = viewModel;
this.DataContext = this;
}
所以很明显,我必须做两件事才能让它工作
因为我是这样绑定用户控件的
this.DataContext = this;
this.CurrentViewModel = viewModel;
this.DataContext = this;
我必须在用户控件类本身上实现INotifyPropertyChange
,并在CurrentViewModel
属性上实现PropertyChanged
调用,如下所示:
private PageSetupEditorViewModel _currentViewModel;
public PageSetupEditorViewModel CurrentViewModel
{
get { return _currentViewModel; }
set
{
_currentViewModel = value;
OnPropertyChanged(nameof(CurrentViewModel));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
tcOrientation.Items.Refresh();
但这并没有完全更新视图,因为我正在使用集合在TabControl
中生成选项卡
在选择组合框的选择更改事件时,我必须刷新选项卡控件.Items
的视图,如下所示:
private PageSetupEditorViewModel _currentViewModel;
public PageSetupEditorViewModel CurrentViewModel
{
get { return _currentViewModel; }
set
{
_currentViewModel = value;
OnPropertyChanged(nameof(CurrentViewModel));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
tcOrientation.Items.Refresh();
这为我解决了问题:)您是否为CurrentViewModel
实现了INotifyPropertyChanged
?能否向我们展示您的ViewModel?我为CurrentViewModel
实现了INotifyPropertyChanged
,但现在更新后我的视图变为空白1)“用户控件顶部有一个组合框”:什么是“顶部”意思?它是在用户控件内部还是外部?2)“我正在更新用户控件的一个属性,这将导致整个视图重新生成”:你能共享所有代码吗?事件处理程序和属性。未看到的代码“经常做一些事实上不应该做的事情。”EdPlunkett我更新了上面的问题。组合在同一用户控件中:)