c# - 如何获取 TextBox 的输入并将其返回到 TextBlock 中

标签 c# wpf mvvm

我是 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/

相关文章:

c# - 如何摆脱 WPF MVVM View 模型中的重复属性

c# - 有没有办法测量 WPF flowdoc 中 block /部分的高度?

c# - 自定义控件可绑定(bind)属性中的值未更新 - Xamarin forms/Prism

c# - 在此对象中 o= sc.ExecuteNonQuery();给我错误 sqlexceptionunhandled 怎么做建议我一个正确的代码

c# - x :TypeArguments and generic List class in XAML 问题

wpf 重写 ContentControl 中的 getHashCode 和 Eqaul

MVVM:负责加载相关数据,在哪一层?

c# - 如何在 wpf 中通过 MVVM 使用 ListView 绑定(bind)获取数据?

c# - 提高网站数据库的搜索性能

c# - 如何将 IEnumerable 模型传递给 MVC 中的局部 View