[英]In mvvm the view doesn't update
我是mvvm概念的初學者。所以我嘗試了一個示例application.it包含兩個文本框是名稱和ID,一個提交按鈕,一個標簽。當我單擊提交按鈕時,它將文本框中的兩個字符串組合並顯示在標簽中。
我可以提交值,在viewmodel中,屬性包含result.but它沒有顯示在view.why ..?
在視圖中包含
<grid>
<TextBox Grid.Column="1" Grid.Row="1" Text="{Binding name}" Height="23" Margin="9" Name="txtname" Width="120" />
<TextBox Grid.Column="1" Grid.Row="2" Text="{Binding id}" Height="23" Margin="9" Name="txtid" Width="120" />
<Button Command="{Binding submit}" Content="submit" Grid.Column="2" Grid.Row="2" Height="23" Name="btnsubmit" Width="75" />
<Label Content="{Binding display}" Grid.Row="3" Height="38" HorizontalAlignment="Left" Name="lbldisplay" Width="192" />
</grid>
view.cs代碼是
public MainWindow()
{
InitializeComponent();
DataContext = new DemoViewModel();
}
在我的viewmodel中包含兩個.cs文件
一個是DemoViewModelInotify.cs.in我寫了inotifypropertychanged的代碼。 另一個是DemoViewModel.cs.this包含屬性和命令。
namespace mvvmdemonixon.ViewModel
{
public class DemoViewModel :DemoViewModelInotify
{
public ICommand submit { get; set; }
public string name { get; set; }
public string display { get; set; }
public int id{get;set;}
public DemoModel model { get; set; }
public DemoViewModel()
{
submit = new DelegateCommand<object>(this.add);
}
public void add(object paramter)
{
string a= mvvmdemonixon.Model.DemoModel.addstring(name, id);
display = a;
}
}
}
我的模型包含
namespace mvvmdemonixon.Model
{
public class DemoModel
{
public static string addstring(string name1, int no1)
{
string display = "The Student Name Is " + name1 + "and Id Is" + no1 + ".";
return display;
}
}
}
在我的app.xaml.cs中
private void OnStartup(object sender, StartupEventArgs e)
{
mvvmdemonixon.MainWindow view = new MainWindow();
view.DataContext = new mvvmdemonixon.ViewModel.DemoViewModel();
view.Show();
}
在我的應用程序xaml中
<Application x:Class="mvvmdemonixon.App"
Startup="OnStartup">
</Application>
提前謝謝..
WPF綁定引擎使用INotifyPropertyChanged
(用於標量屬性)和INotifyCollectionChanged
(用於集合屬性)接口來反映已在綁定數據源(視圖模型)中進行的更改。
這個:
public string display { get; set; }
意味着,任何屬性設置都不會通知視圖,因為setter的代碼不包含任何通知。 代碼應該是這樣的:
public string display
{
get { return _display; }
set
{
if (_display != value)
{
_display = value;
OnPropertyChanged("display");
}
}
}
private string _display;
其中OnPropertyChanged
引發INotifyPropertyChanged.PropertyChanged
事件。
對於視圖模型中的其他視圖綁定屬性也是如此,它應該更新視圖。
您需要在ViewModel中實現INotifyPropertyChanged 。 並從每個屬性設置器中提升屬性更改事件。
你遺失了兩件事。 第一件事是你的View的綁定是OneTime。 第二件事是ViewModel在屬性更改時不通知。
要解決第一個問題,您必須更新xaml,如下所示。
<Label Content="{Binding display, Mode=OneWay}" Grid.Row="3" Height="38" HorizontalAlignment="Left" Name="lbldisplay" Width="192" />
要解決第二個問題,您必須實現INotifyPropertyChanged 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.