我在我的WPF应用程序中跟踪代码。我在使用ContentPresenter控件更改SelectedAccountType组合框值时动态呈现MainWindow中的用户控件。 我在UI中的MyProperty文本框中输入一些值,然后单击MainWindow上的Save按钮。但是我没有在Save方法的MainWindowViewModel.cs中看到这个值(即点击Save按钮)。 我的所有ViewModel都扩展了这个抽象类:
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
我在这里想念的是什么?
感谢。
这是我的代码:
MainWindow.xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MainViewModel="clr-namespace:Test.ViewModel"
xmlns:ViewModel="clr-namespace:Test.ViewModel.AccountTypes"
xmlns:View="clr-namespace:Test.View" x:Class="Test.MainWindow"
xmlns:Views="clr-namespace:Test.View.AccountTypes"
xmlns:v="clr-namespace:Test.View.AccountTypes"
xmlns:vm="clr-namespace:Test.ViewModel.AccountTypes"
Title="{Binding DisplayName, Mode=OneWay}" ResizeMode="CanResize" WindowStartupLocation="CenterScreen">
<Window.DataContext>
<MainViewModel:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<StackPanel Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Horizontal" Height="28" Width="auto" Margin="5,0,0,0">
<ComboBox Width="360" Margin="1,0" ItemsSource="{Binding AccountTypes}" DisplayMemberPath="Code" SelectedValuePath="ID" SelectedItem="{Binding SelectedAccountType,
Mode=TwoWay}" TabIndex="0" />
</StackPanel>
<ContentPresenter Content="{Binding CurrentViewModel}">
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type ViewModel:AC1ViewModel}">
<Views:AC1View/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:AC2ViewModel}">
<Views:AC2View/>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
MainWindowViewModel.cs
public object CurrentViewModel
{
get
{
return m_currentViewModel;
}
set
{
m_currentViewModel = value;
OnPropertyChanged("CurrentViewModel");
}
}
public AccountType SelectedAccountType
{
get
{
return m_selectedSearchAccountType;
}
set
{
m_selectedSearchAccountType = value;
if (SelectedAccountType.Code == "AC1")
{
CurrentViewModel = new AC1ViewModel();
}
else if (SelectedAccountType.Code == "AC2")
{
CurrentViewModel = new AC2ViewModel();
}
}
}
public void Save()
{
Type sourceType = CurrentViewModel.GetType();
PropertyInfo[] sourcePI = sourceType.GetProperties();
Type destinationType = securityDetails.GetType();
PropertyInfo[] destinationPI = destinationType.GetProperties();
string propertyName = string.Empty;
object propertyValue = null;
foreach (var pinfo in sourcePI)
{
propertyName = pinfo.Name.Trim();
propertyValue = pinfo.GetValue(CurrentViewModel)
}
}
AC1View.xaml:
<TextBox HorizontalAlignment="Left" Height="23" Margin="1,1,0,0" VerticalAlignment="Top" Width="230" TabIndex="1" Text="{Binding MyProperty,UpdateSourceTrigger=PropertyChanged}" />
AC1ViewModel.cs
public class AC1ViewModel
{
private string m_myProperty = "";
public AC1ViewModel()
{
}
public string MyProperty
{
get
{
return m_myProperty;
}
set
{
m_myProperty = value;
}
}
}