询问者
MVVM中, Model绑定问题

问题
-
我的Model中有一个属性, 比如:
private double number;public double Number
{
get { return number; }
set { number = value; }
}
我在ViewModel中如下使用:
public MainModel Model
{
get { return model; }
set
{
model = value;
}
}
问题: 为什么我的textbox的text绑定到viewModel中的属性Model的Number后, 动态改变Number, text没有变化?
我不是已经 OnPropertyChanged("Model");通知 这个属性更改了吗?
木子纵横 Email: QQQ520qq@sina.com qq: 474540695
全部回复
-
我的view绑定到viewmodel,
namespace CustomControlDemo.ViewModels { public class MainViewModel : ViewModelBase { public MainViewModel() { } // private MainModel model = new MainModel(); public MainModel Model { get { return model; } set { model = value; OnPropertyChanged("Model"); } } private ICommand addNumeric; public ICommand AddNumeric { get { if (addNumeric == null) { addNumeric = new DelegateCommand(Add); } return addNumeric; } set { addNumeric = value; } } private void Add() { Model.Text = "test1"; } } }
namespace CustomControlDemo.Models { public class MainModel { public MainModel() { // Blank Text = "test"; } private string text; public string Text { get { return text; } set { text = value; } } } }
<Grid DataContext="{Binding Source={StaticResource MainViewModelDataSource}}"> <Grid Margin="0,20.96,0,0" d:LayoutOverrides="Width"> <StackPanel VerticalAlignment="Top" Height="44" Margin="203,2.04,0,0" Orientation="Horizontal" HorizontalAlignment="Left" Width="189"> <Button x:Name="button" Margin="0" Content="Add" Command="{Binding AddNumeric, Mode=Default}" Width="80"/> <TextBox x:Name="textBox" Text="{Binding Model.Text, Mode=Default}" TextWrapping="Wrap"/> </StackPanel> </Grid> </Grid>
木子纵横 Email: QQQ520qq@sina.com qq: 474540695 -
大概知道是什么意思了
3个层次
view中的textbox.text绑定到viewModel的Model.Number,而viewModel的Model实际引用的是model中类MainModel实例
你已经在viewModel的Model属性调用了OnPropertyChanged("Model")方法,实际上关键的是model中类MainModel.Number属性的访问器你没调用OnPropertyChanged("Number")
OnPropertyChanged("Model")被调用只会发生在viewModel的Model属性的引用(类似于地址)被改变时,这样虽然你的model.Number值改变了,但是实际的model对象的引用没发生改变