我是 MVVM 的新手,我想在文本框中输入一个字符串,然后它会在另一页的文本 block 中返回。
在我的 Views 文件夹中,我在 xaml 中有这段代码,这是我要输入的文本框:
<TextBox x:Name="date" Text="{Binding Date}" Grid.Row="0" TextAlignment="Right" TextWrapping="Wrap" Margin="0 10 0 1" Padding="1" />
这是一个具有文本 block 的不同 wpf 页面,我希望在文本框中键入的内容显示在此处:
<TextBlock Grid.Row="0" TextAlignment="Right" TextWrapping="Wrap" Margin="0 0 0 2" Padding="1" Text="{Binding Date}" />
在我的模型文件夹中,我有类 Data Entry,如下所示:
public class DataEntry
{
public string Date { get; set; }
}
在我的 ViewModels 文件夹中我有:
namespace FumeHood1._0._0.ViewModels
{
public class MainViewModel : INotifyPropertyChanged
{
public DataEntry DataEntry { get; set; }
private string date;
public string Date
{
get { return date; }
set
{
date = value;
OnPropertyChanged(nameof(Date));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我到处找,找不到合适的方法。如果有人能提供帮助,那就太棒了。只是试图让这个 MVVM 模式起作用并且对我来说更有意义。
最佳答案
首先,设置 View 的 DataContext
。
public partial class MainWindow : Window
{
public MainWindow() {
InitializeComponent();
DataContext = new MainViewModel();
}
}
或者在 xaml 中:(不能同时)
<Window>
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
</Window>
并确保在两个页面中使用相同的 MainViewModel 实例。
其次,仔细配置您的绑定(bind)以按预期运行:
<TextBox Text="{Binding Date, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}"/>
<TextBlock Text="{Binding Date}" />
请注意,UpdateSourceTrigger=PropertyChanged
确保在用户键入时更新 View 模型属性。 Mode=OneWayToSource
仅从 TextBox Text 属性更新 View 模型属性,反之则不然。
关于c# - 如何获取 TextBox 的输入并将其返回到 TextBlock 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51160162/