我已经实现了一个用户控件,其中我将 DataContext
绑定(bind)到自身,如下所示...
this.DataContext = this;
用户控件顶部有一个组合框。关于它的选择更改事件。我正在更新 UserControl
的属性,这应该会导致重新生成整个 View ,包括 TabControl
和 TextBoxes
中的一些选项卡。
在选择更改事件中,我正在像这样更新属性...
this.CurrentViewModel = viewModel;
以下是 View 中的一些示例 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}">
在 TabControl 内部...
<TabControl.ContentTemplate>
<DataTemplate>
<Grid>
<StackPanel
Orientation="Horizontal"
Margin="0,0,0,5">
<TextBlock
Text="Page Width:"
Style="{StaticResource tbDataLabel}"
Margin="0,0,34,0"
/>
<Border
Width="98"
CornerRadius="5"
BorderBrush="#CCCCCC"
Background="White"
BorderThickness="1"
Margin="7,0,0,0"
>
<xctk:DecimalUpDown
x:Name="pageDimWidth"
Value="{Binding Path=PageWidth, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
Validation.Error="page_Error" Increment="0.10"
ParsingNumberStyle="Float"
Style="{StaticResource dudValues}"
d:DataContext="{d:DesignInstance dtOs:PageSizeOrientationViewModel}"
/>
更新1:
这是 CurrentViewModel
属性
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));
}
谁能告诉我我在这里缺少什么......
更新2: 分享组合选择更改事件:
private void cmbPageSetupTemplate_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_errors = 0;
var validPageSetup = cmbPageSetupTemplate.SelectedItem as PageSetupEditorViewModel;
CurrentViewModel = viewModel;
this.DataContext = this;
}
最佳答案
显然,我必须做两件事才能使其发挥作用。
因为我像这样将用户控件绑定(bind)到自身......
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));
}
但这并没有完全更新 View ,因为我使用集合在 TabControl
中生成选项卡。
我必须在选择 ComboBox
的选择更改事件时使用此刷新 TabComtrol.Items
的 View ,如下所示:
tcOrientation.Items.Refresh();
这解决了我的问题:)
关于c# - 更改 ViewModel 对象不会反射(reflect)对 View 的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39271057/